Home > Enterprise >  c Two Classes Refering To Each Other
c Two Classes Refering To Each Other

Time:01-20

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

CodePudding user response:

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.

  •  Tags:  
  • Related