Why don't you simply add it to the constructor of the every child class?
If you want to avoid writing it every time in the constructor (or even skipping or inheriting it) then you could use CRTP:
class Parent {
public:
Parent(){};
virtual void helloWorld() = 0; // no standard hello...
};
template <typename Par>
class ParentCRTP: public Parent {
public:
ParentCRTP(){
Par::doHelloWorld();
};
virtual void helloWorld(){
Par::doHelloWorld();
}
};
class Child : public ParentCRTP<Child> {
public:
static void doHelloWorld(){ // childs implementation of helloWorld
std::cout << "Hello, World!\n";
};
};
This approach will not give you a pointer to the child class in your child's hello method - at this point class instance is only Parent
instance, no valid Child
pointer can be obtained. To force an execution of Child
's method after construction you can only use two stage initialization: First you create class instance using a constructor, and then initialize it using separate method.
Apart from that, problem like this is probably a hint to re-think your design. You shouldn't force your classes to initialize itself in a given way.