Search code examples
c++inheritanceshared-ptr

Shared Pointer for parent and child


I have a problem with the initialization of some classes. Simplified code looks like:

class Base
{
    Base(int)
};

class BaseChild : public Base
{
};

class mainWindow
{
    boost::shared_ptr<Base> pBase;
    void init();
};

void mainWindow::init()
{
    this->pBase = boost::shared_ptr<Base>(new Base(12));
    this->pBase = boost::shared_ptr<Base>(new BaseChild(12));
}

So the problem is with initialization of BaseChild class which is child from Base class. What am I doing wrong? I thought that parentral class pointer can point on child class.

Generaly my program has to work in such way:

  • When it starts, there is initialization of parental class (in above example: this->pBase = boost::shared_ptr<Base>(new Base(12));). This already works.

  • In some case, when some flag change its value, pointer which point on parental class object should be change to point on child class object.


Solution

  • You miss a constructor that takes int in BaseChild. Also constructor in Base is private, which makes it unusable outside Base class.
    Try

    class Base
    {
    public:
         Base(int);
    };
    
    class BaseChild : public Base
    {
    public:
        BaseChild(int);
    };