Click to See Complete Forum and Search --> : Please help me with this simple program.


brave heart
April 10th, 2002, 03:38 AM
#include <iostream>

using namespace std;

class CFather{
public:
CFather() { InitInstance(); }
virtual void InitInstance(){
cout << "I am the father." << endl;
}
};

class CSon : public CFather{
public:
void InitInstance(){
cout << "I am the son." << endl;
}
};

int main()
{
CSon son;
return 0;
}



The program's output is:
I am the father.

How can I make the CFather's constructor invoke the InitInstance function defined in the CSon?
Thanks a lot!

Graham
April 10th, 2002, 03:54 AM
You can't. At the time the CFather ctor is called, the object is not yet a CSon - the vtable hasn't been set up and the virtual function mechanism doesn't work.

How you get around it depends heavily on what you actually want to do in your InitInstance. Most of the time, virtual init methods are not necessary if your class hierarchy is designed well.

He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf