Search code examples
c++header-filessubclassing

Forward Declare a Subclass


I have a Base class A in a header file A.h

class A{};

in A.cpp I have several subclasses:

class B: public A{};
class C: public A{};

I would like to instantiate types B and C in a separate file but I can't see how unless I include A.cpp in my other files. If I forward declare B and C in A.h like this:

class B;
class C;

Then the instantiating class doesn't know its derived from A. How would I solve this issue?

Thanks, Eric


Solution

  • You need to declare A in header file for example A.h and include that file into B.cpp and C.cpp, also if you have some non inline functions in A (functions that defined in A declaration are implicitly inline) you should create A.cpp, include A.h there as well and define those functions in A.cpp