How do virtual destructors work?

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2010-04-22T11:52:16Z Indexed on 2010/04/22 11:53 UTC
Read the original article Hit count: 110

Filed under:

I am using gcc. I am aware how the virtual destructors solve the problem when we destroy a derived class object pointed by a base class pointer. I want to know how do they work?

class A
{
      public:
      A(){cout<<"A constructor"<<endl;}
     ~A(){cout<<"A destructor"<<endl;}

};

class B:public A
{
      public:
      B(){cout<<"B constructor"<<endl;}
      ~B(){cout<<"B destructor"<<endl;}
};       

int main()
{
  A * a = new B();
  delete a;    
  getch();
  return 0;   
} 

When I change A's destructor to a virtual function, the problem is solved. What is the inner working for this. Why do I make A's destructor virtual.

© Stack Overflow or respective owner

Related posts about c++