The constructor can not be a virtual function, this is obviously, after all, virtual functions are corresponding to a virtual function table, virtual function table is the existence of object memory space, if the constructor is virtual, you need a virtual function table to call, but the class has not materialized without memory space there is no virtual function table, this is simply a dead loop.
But destructors are defined as virtual functions, which is why, write a very simple example to understand:
classAA { Public: AA () {}; ~AA () {fun2 ();}; Virtual voidfun1 () {cout<<"Base construct"<<Endl; } Virtual voidfun2 () {cout<<"Base Destruct"<<Endl; }};classBb: PublicAA { Public: BB () {fun1 ();}; ~BB () {fun2 ();}; voidfun1 () {cout<<"Derive construct"<<Endl; } voidfun2 () {cout<<"Derive Destruct"<<Endl; }};intMain () { for(inti =0; I <1; i++) { //AA A;BB B; } return 0;}
Output Result:
Therefore, it can be seen that when the derived class object is constructed, the constructor of the base class is called before the constructor of the derived class is called, and the destructor of the derived class is called before the base class destructor is called.
In fact, this is very well understood, the members of a derived class are composed of two parts, part of which is inherited from the base class, and part of it is defined by itself. Then, when instantiating an object, first use the base class constructor to initialize the members inherited from the base class, and then initialize the part that you define with the derived class constructor.
At the same time, not only the constructor derived class is responsible for its own part, the destructor is also, so the destructor of the derived class will only deconstruct its own part, when the destructor of the base class is not a virtual function, you can not call the base class destructor destructor from the base class to inherit from the part of the member, so there will be only half of the Cause a memory leak.
Therefore, destructors are defined as virtual functions.
Why do you want to define a destructor as a virtual function in C + +