0

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 :)

  • can you explain the problem in more detail? btw you can use forward declaration to avoid circular compilation dependency – Roshan M Jan 19 '22 at 17:30
  • Check this [StackOverflow answer](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes). – biqarboy Jan 19 '22 at 17:34

1 Answers1

5

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.

Useless
  • 64,155
  • 6
  • 88
  • 132