Search code examples
c++classinheritancesubclassbase-class

How to create a subclass object in the baseclass


what I am trying to do is:

  • Have a Sub class object in Base class.
  • Make Sub class access Base class'es variables

Base.h

#include "Sub.h"
class Base
{

Sub subobject
int x;
}

Sub.h

#include Base // to acces x from .cpp file
class Sub: public Base
{
void changevar();
}

Sub.cpp

#include "Sub.h"
// I tried to include base in here but that did not work either
void Sub::changevar()
{
x++;
}

But I keep getting undefines base class and undefined undeclared x error. How can I solve this?


Solution

  • What if you store the suboject as a pointer instead?

    You will need to also

    • Forward declare your Sub class in Base.h before your Base class
    • Include the Sub.h in your Base.cpp file
    • Call new for it to have something pointing to it and obviously a corresponding delete (note: not in the constructor as that will create a loop where a Base creates a Sub that creates a Base that creates a Sub)

    However it seems a bit odd a base have a reference to a subclass, it breaks the whole point of inheritance and if you are needing to do this, then you should reconsider if what you are doing is correct.

    Also note, the Sub will have its own Base as part of it so the Base part of the subobject will not be the same as the outer Base.

    e.g. if Base itself had an integer called Y, then we would have the Y of Base, but a separate Y for subobject also.

    Maybe explain a bit better why the base class needs a copy of a subclass?

    Rough code sketch:

    Base.h

    #include "Base.h"
    
    class Sub;
    
    class Base
    {
    public:
        Sub* subobject;
        Base();
        ~Base();
    
        void createSub();
    };
    

    Base.cpp

    #include "Base.h"
    #include "Sub.h"
    
    Base::Base()
    {
        subobject = new Sub();
    }
    
    Base::~Base()
    {
        delete subobject;
    }
    
    void Base::createSub()
    {
        if (subobject)
            return;
    
        subobject = new Sub();
    }
    

    Sub.h

    #include "Base.h"
    
    class Sub : public Base
    {
        void changevar();
        int x = 0;
    };
    

    Sub.cpp

    void Sub::changevar()
    {
        x++;
    }