Possible Duplicate:
Calling virtual method in base class constructor
Calling virtual functions inside constructors
How can I call a protected virtual method from a constructor in C++?
class Foo
{
Foo(){
printStuff(); // have also tried this->printStuff()
}
protected:
virtual void printStuff() {}
}
class ExtendedFoo : public Foo {
protected:
virtual void printStuff() { cout << "Stuff" << endl;}
}
...
ExtendedFoo exFoo; // should print "Stuff"
There’s no problem in calling a protected function from the constructor – just do it. However, what you seem to be wanting is to call into a concrete derived class’ implementation of it, e.g., ExtendedFoo’s, since it’s virtual – right? That’s a no-go, since inside the Foo constructor, the object being created is still of type Foo, not ExtendedFoo, so no virtual dispatch can take place. If the protected function isn’t pure virtual, the Foo implementation is called, i.e., the constructor will call the class’ own implementation.