During base class construction, virtual functions never go into derived classes and the object behaves as only the respective members of base class need to be called.
Cannot call any member function before constructor completes: Because base class constructors execute before derived class constructors, this means that derived class data members have not been initialized yet when base class constructor is running. If virtual functions called during base class construction invoke functions in the derived classes, then those derived class functions may refer to derived class data members, but those data members were not yet initialized. That may cause undefined behavior in program. An object doesn’t become part of a derived class until execution of a derived class constructor completes.
VPTR Mechanism: Also, the virtual tables and virtual pointers are not yet initialized because the derived class constructor has not run.
Class cease to exist after destructor is run: The same reason applies during destructor execution. Once a derived class destructor has run, the object’s derived class data members become undefined values, so compiler assumes them as if they no longer exist. Hence, the functions only from Base class are called.
In the following example, class calls virtual function “func( )” from base class constructor and destructor.
#include <iostream> //main header
using namespace std; //for namespace
class MFBase
{
public:
MFBase()
{
cout << "Base Constructor" << endl;
func();
}
virtual void func()
{
cout << "Base::func() " << endl;
}
virtual ~MFBase()
{
func();
cout << "Base Destructor" << endl;;
}
};
class MFDerived : public MFBase
{
public:
Derived()
{
cout << "Derived Constructor" << endl;
}
virtual void func()
{
cout << "Derived::func() " << endl;
}
~MFDerived()
{
cout << "Derived Destructor" << endl;
}
};
int main()
{
MFBase *bptr = new MFDerived;
bptr->func();
delete bptr;
return 0;
}
The output is:
Base Constructor
Base::func()
Derived Constructor
Derived::func()
Derived Destructor
Base::func()
Base Destructor
Clearly, virtual function mechanism is not working and only local functions are being called.