c++ Two Classes Refering To Each Other

i'm working with c++.
I need to create two classes that refering to each other.
Something like this:

class A {
  private:
    B b; 
   //etc...
};
class B {
  private:
    A a; 
   //etc...
};

How can i do that?
Sorry for my bad English and thanks you for helping me :)

Upvotes: 0

Views: 74

Answers (1)

Useless
Useless

Reputation: 67852

You can't do that even in principle, because a single A object would contain a B which contains another A, which contains another B and another A ...

If you just want a reference, you can simply do

class B; // forward declaration

class A {
  B& b_;  // reference
public:
  explicit A(B& b) : b_(b) {}
};

class B {
  A a_;
public:
  B() : a_(*this) {}
};

Now each B contains an A which refers to the B in which it sits.

Do note however that you can't really do anything with b (or b_) inside A's constructor, because the object it refers to hasn't finished creating itself yet.

A pointer would also work - and of course A and B can both have references instead of B containing an immediate object.

Upvotes: 5

Related Questions