Talking about the case of calling virtual functions in constructors, only single inheritance is discussed, regardless of virtual inheritance and multiple inheritance. Test platform: VS2013 + win7x64
An example: #include <stdlib.h>
#include <stdio.h>
Class Base
{
Private
int __data;
Public
Base ()
{
This->func ();
}
Public
virtual void Func ()
{
printf ("Base::func");
}
};
Class Deri:public Base
{
Public
Deri ()
{This->func ();
}
Public
virtual void Func ()
{
printf ("deri::func\n");
}
};
int main (int argc, char** argv)
{
Deri D;
GetChar ();
return 0;
}
Output: Base::funcderi::func
First, we discuss the construction of Object D. 1 first constructs the base class part, calls the base class base the constructor, at this time, the derived class part has not produced, when the virtual table should be the binding base class, naturally calls the Base::func ()
2 again constructs the derived class part, at this time, the virtual table changes, binds on the derived class, calls Deri::func ()
Although there is an overloaded Func function in a derived class, the member data of the derived class is not initialized when you construct the base class part, and if you call Func in a derived class, it can cause errors, memory out of bounds, or even crashes.
In the function, you can print the virtual table address:
--Base::func () int* VTL = (int*) * ((int*) this), Std::cout << "Base:" << this << "VTable:" << vtl << Std::endl;
--Deri::func () int* VTL = (int*) * ((int*) this), Std::cout << "Deri:" << this << "VTable:" << vtl << Std::endl;
Output: base:0028f980 vtable:003fdc78
deri:0028f980 vtable:003fdc98
found that the address of the virtual table is constantly changing.
Calling virtual functions in C + + constructors