Consider a base class that has an attribute
class Base
{
protected:
AttributeBase * elementPtr;
...
};
And a derived class
class Derived : public Base
{
...
};
Also I have a class AttributeDerived
which derives from AttributeBase
When I create an object of the class Base
I would like elementPtr
to be initialized in this way:
elementPtr = new AttributeBase()
But when I create an object of the class Derived
I would like elementPtr
to be initialized in this way:
elementPtr = new AttributeDerived()
What is the cleanest way to do that?
You could add a protected
constructor to Base
which allows the derived class to pass an elementPtr
to use:
Base (AttributeBase* elementPtr) : elementPtr(elementPtr)
{}
Then in your derived class, call that constructor:
Derived() : Base(new AttributeDerived())
{}
If you use C++11, you could then have other Base
constructors delegate to the protected one to limit code duplication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With