I have a requirement where I want to initialize a Base class member in derived class.
class SuperBase
{
public:
virtual void Set();
};
class Base:public SuperBase
{
protected:
int *pVal;
public:
void Set()
{
//Some Logic
}
};
class Derived1: public Base
{
public:
// I want to Initialize Base::pVal here and after
// that I want to have this value in Set() of Base.
};
class Derived2: public Base
{
//...Same functionality as Derived1;
//...
};
int main()
{
SuperBase *s = new Derived1;
// Here when I create a Derived1 object automatically,
// the value for pVal will be initialized
s->Set();
//After calling this Set, I want to get the pVal value access in Set.
}
I know that it is an easy thing to do. But these are the things which I cannot use for this problem:
I cannot use Constructor Initializer List for passing values from derived class to Base [I know that I can easily do this through Constructor Initialiser List but there is a requirement where I don't want the existing Class Constructor]
I have tried using CRTP[curiously recurring template pattern], but that is also not suitable as it uses a type of static binding, and in higher view, I have to decide at run time which class object to call Derived1,Derived2.
I also don't want to write any get() in Derived1,Derived2 as I want to only assign values there. This is also a part of my requirement.
I want the Set logic to be only present in Base class and if there is any special case of Set, then I will override Set in Derived classes, otherwise I will access it from Base.
Any Suggestions??? Any Design Patterns??
nullptr? - lapkpValin your derived constructors (or anyplace else for that matter)? It's protected, not private; you have access to it. Or is the magic puzzle piece you neglected to mention thatBaseneeds it in its constructor ? - WhozCraig