Search code examples
c++referenceconstruction

C++ referring to an object being constructed


In C++ I have a reference to an object that wants to point back to its owner, but I can't set the pointer during the containing class' construction because its not done constructing. So I'm trying to do something like this:

class A {
   public:

     A() : b(this) {}
   private:
     B b;
};

class B {
   public:
     B(A* _a) : a(_a) {}
   private:
     A* a;
};

Is there a way to ensure B always gets initialized with an A* without A holding a pointer to B?

Thanks


Solution

  • Try this:

    class A;
    
    class B {
    public:
      B(A *_a) : a(_a) {};
    
    private:
      A* a;
    };
    
    class A {
    public:
      A() : b(this) {};
    
    private:
      B b;
    
    };
    

    Since B is contained completely in A, it must be declared first. It needs a pointer to A, so you have to forward-declare A before you declare B.

    This code compiles under more-or-less current versions of g++.