How to use class which defined below?

c++, class

Solution

This is not possible. You need to use a pointer or a reference in one of the classes.

class B; // forward declare class B
class A {
public:
  B * b;
};

class B {
public:
  A a;
};

As to why it isn't possible: A contains a B contains an A contains a B ... There's no end to the recursion.

If you're used to languages (such as e.g. java) where all object variables are pointers/references by default, note that this is not the case in c++. When you write `class A { public: B b; };` a complete `B` is embedded into A, it is not referred to within A. In C++ you need to explicitly indicate that you want a reference (`B & b;`) or a pointer (`B * b;`)

Problem

``` class A{ public: B b; }; class B{ public: A a; }; ``` I can't write in A class "B b" because class B defined below. Is any way to make it work? thanks

Original source