Reputation: 118
I'm running into an inheritance problem and I don't know if my solution is elegant. I have classes like this
class Var
{
public:
virtual void doSomething();
}
class DerivedVar : public Var
{
public:
virtual void doSomething();
void doSomethingElse();
}
I also have MyDerived that inherits from MyBase. MyBase has a member of type Var while MyDerived needs to have a member of DerivedVar so it can call doSomething(). Currently, I'm using template to solve this problem
template<typename VarType>
class MyBase
{
protected:
VarType var;
public:
MyBase() { var.doSomething(); }
}
class MyDerived : public MyBase<DerivedVar>
{
public:
MyDerived() : MyBase() { var.doSomethingElse(); }
}
I want to know if there's a better way to do this (eg. without the need of using template)
Upvotes: 3
Views: 204
Reputation: 145269
If you want or need to avoid the templating then you need to allocate the covariant type data member dynamically.
A good approach is then to pass a factory up the constructor chain (it can be a defaulted constructor argument), and invoke it in the base class.
An ungood approach, but very popular in the early 1990s, is to use two-phase initialization.
OK, I anticipated issue that you have not yet run into.
But you will. ;-)
That said, if you can make the template approach work that's probably best.
Most direct solution, least amount of workarounds and code and design adaptions.
Upvotes: 1