I have an abstract base class Base
that contains a pointer to another abstract base class BaseDataClass
. I have derived classes for both classes, I'll call them Derived
and DerivedDataClass
. The Base
does not know that DerivedDataClass
exists, and in any case, I intend to later have multiple combinations of Base
and BaseDataClass
subclasses . In the derived class, I want the pointer to be set to an instance of the derived data class, but I don't want to accidentally be able to assign the pointer later on so I made it const
. This obviously keeps me from assigning the pointer using new
in the derived class's constructor. Is there a neat way to accomplish this while keeping the pointer const?
class BaseDataClass
{
public:
BaseDataClass(){}
//some pure virtual methods
};
class Base
{
public:
Base(){}
//some pure virtual methods
protected:
BaseDataClass * const data; //compiler complains if this isn't set
};
//// elsewhere
class DerivedDataClass : public BaseDataClass
{
public:
DerivedDataClass(){}
};
class Derived : public Base
{
public:
Derived(){
data = new DerivedDataClass(); //also does not compile obviously
}
};