3

I have the following case:

class_a.hpp:

#include "class_b.hpp" // is this "include" mandatory?
class class_a{
private:
    class_b b;
};

class_a.cpp:

#include "class_b.hpp"
//code that uses member variables and functions from class_b 

class_b.hpp:

class class_b{};

Is it possible to get rid of #include "class_b.hpp" in the class_a.hpp? Since it is just declaration, why I can not just use forward declaration and not including it? (I tried but it was not compiled)

Of Course I have included class_b.hpp in the class_a.cpp.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160

2 Answers2

9

Since class_b needs to be stored inside class_a without any indirection (e.g. a pointer), the size of class_b needs to be known during the declaration of class_a. In order to know the size, the declaration of class_b needs to be available: the #include directive is therefore required.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
3

why I can not just use forward declaration and not including it?

With only forward declaration the class type class_b will be incomplete type. But to be declared as a non-static class data member, need it to be complete, the size and layout of it must be know.

Any of the following contexts requires class T to be complete:

...
declaration of a non-static class data member of type `T`;
...

(In general, when the size and layout of T must be known.)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405