0
#include <iostream>
using namesapce std;
class A
{
  public:
         virtual ~A(){cout<<"delete A"<<endl};
};
class B: public A
{
  public:
         B(int n):n(n){}
         void show(){cout<<n<<endl;}
         ~B(){cout<<"delete B"<<endl;}
  private:
         int n;

}
int main()
{
   A *pa;
   B *pb = new B(1);
   pa = pb;
   delete pa;
   pb->show();
   return 0;
}

when destructor of calss A is virtual ~A(){...},the output of program: delete B delete A 1 when destructor of class A is ~A(){...}, the output of progarm: delete A 0 why the value of n is different, when destructor of class A is virtual or non virtual? when call destructor of B to destroy object, why the calss member n is still existent?

PengWin
  • 9
  • 4

2 Answers2

1
 A *pa;
 B *pb = new B(1);
 pa = pb;

This is called upcasting. Whenever upcasting is done base class destructor should be made virtual.

Without virtual base destructior, delete pa will call only base class destructor which is undesirable, because it derived class object will never be destroyed and results in memory leak.

Virtual destructor of base class will call first derived class destructor and then it will destruct itself which is desired behavior and does not cause any leak because of upcasting.

Prafull Ladha
  • 12,341
  • 2
  • 37
  • 58
1

Your program exhibits undefined behavior. That's the only answer to your "why" question.

Firstly, if destructor of A is not virtual, then doing delete pa in your code leads to undefined behavior. Trying to delete object of type B through a pointer to parent type A * leads to undefined behavior of the destructor of A is not virtual.

Secondly, pb->show() appears to be an attempt to call a method of an already destroyed object. The behavior is undefined as well, regardless of whether destructors are virtual or not.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765