Please consider this class hierarchy:
#include <iostream>
struct Base
{
Base(int arg1, int arg2, int arg3, int arg4)
{
std::cout << "Base::Base:" << arg1 << "," << arg2 << "," << arg3 << "," << arg4 << std::endl;
}
void BaseDoWork()
{
std::cout << "Base::BaseDoWork" << std::endl;
}
};
struct Derived1:public Base
{
Derived1(int arg1, int arg2, int arg3, int arg4):Base(arg1, arg2, arg3, arg4){}
void DerivedDoWork()
{
BaseDoWork();
}
};
struct Derived2:public Derived1
{
Derived2(int arg1, int arg2, int arg3, int arg4):Derived1(arg1, arg2, arg3, arg4){}
};
int main(int argc, char *argv[])
{
Derived2 myDerived2(1,2,3,4);
myDerived2.DerivedDoWork();
return 0;
}
The class Derived1 has more coupling than I would like: it has to know how to construct a "Base" class. In a deep hierarchy this would mean propagating the arguments for the "Base" class constructor all the way down the class hierarchy. A change to the "Base" class constructor would require a change to all the derived classes.
My objectives for this class hierarchy are:
Derived1 expects a BaseDoWork() method in the base class but does not need to know how to construct the base class.
Derived2 knows how to construct a "Base" class.
Ideally I'd like to make Derived1 a template accepting any base class with an accessible "BaseDoWork()" method, along these lines:
template <T> struct Derived1:public T
{
void DerivedDoWork()
{
BaseDoWork();
}
};
But if I instantiate the above template as Derived1<Base>
I can't see how to construct "Base" class without adding knowledge of "Base" constructor arguments to Derived1.