dje1990 dje1990 - 19 days ago 5
C++ Question

c++ base class contain instance of a derived class

I was wondering if someone could explain to me how I might be able to implement something similar to this:

namespace advanced_cpp_oop
{
class A
{
B b;
};

class B : public A
{
};
}

int main()
{
}


Where an instance of a base class can contain an instance of a derived class? When the above code is compiled the following error is generated:

g++ advanced_cpp_oop.cpp
advanced_cpp_oop.cpp:8:5: error: ‘B’ does not name a type


The (almost) equivalent Java code which does compile is:

public class AdvancedCppOop
{
public static void main(String[] args)
{
A a;
}
}

class A
{
B b;
}

class B extends A
{
}


Thanks

Answer

You need to a pointer and a forward declaration:

namespace advanced_cpp_oop
{
  class B;

  class A
  {
    B* b;
  };

  class B : public A
  {
  };
}

In your C++ code, you are creating an instance of your class B inside class A, which is not possible since the compiler does not yet know anything (especially not the size) of class B.

With the code from my answer, you need to dynamically allocate an instance of class B and assign it to the b pointer somewhere else in your code.

On a side note, from design perspective, this does not really make sense since a parent class should not depend on a sub class.

Comments