In fact, this is a principle of effect c ++, but it is silly and stupid, always forget, write down the tunnel to remember.
I:
Class
{
Public:
~ A ()
{
Cout <_ function _ <Endl;
}
};
Class B: public
{
Public:
~ B ()
{
Cout <_ function _ <Endl;
}
};
Int _ tmain (INT argc, _ tchar * argv [])
{
A * P = new B; // when P is released, it is called only the destructor of A because it is of the type.
Delete P;
Return 0;
}
So the key to the problem is: when a subclass inherits from this parent class, and this parent class does not use a virtual destructor, this happens when a * P = new B is used. When P is parsed, the program only calls the destructor of Class, instead, I would never think of calling Class B.
II:
Class
{
Public:
Virtual ~ A ()
{
Cout <_ function _ <Endl;
}
};
Class B: public
{
Public:
Virtual ~ B ()
{
Cout <_ function _ <Endl; // a miracle occurred. After the subclass calls its own destructor, it will continue to automatically call the destructor of the parent class.
}
};
Int _ tmain (INT argc, _ tchar * argv [])
{
A * P = new B;
Delete P;
Return 0;
}
When the destructor of A is declared as virtual, The destructor of its subclass will overload it, even if
A * P = new B; in this case, no sub-class destructor is called.
Note:
Used
After the subclass calls its own destructor, it will continue to automatically call the destructor of the parent class.