On 31 Jan 2006 08:24:05 -0800, ""
<> wrote:
>Say I have a class A, and a class B that inherits from A. Now A (and B)
>has a virtual destructor and a virtual function F();
>
>If I now make these statements
>
>A* ptrA = new B;
>ptrA->F();
>delete ptrA
>
>then in the statement ptrA->F(), by means of the polymorph behavior,
>the F() of class B is called. But the F() of class B only. And in
>delete ptrA, both destructors of class A and B are called.
>
>Is this right? Because then the two statements behave differently.
>Somehow, for a moment, I was thinking that in the call ptrA->F(), both
>virtual functions of class A and B should be processed.
The destructor is a special function. A is a base class of B,
therefore it is contained by B and has to be destroyed much like any
other member variables of B have to be destroyed when B is destroyed.
If you delete a B* directly, its A part is also deleted -- even when
A's destructor is not virtual.
But the destructor of A (and B) is virtual, so calling delete on an A*
calls B's destructor, and during the normal destruction of B, A's
destructor is also called. It is therefore the same mechanism as
calling an ordinary function; the only difference is that the
destructors are "chained".
--
Bob Hairgrove