Virtual destructor - How does it work?

Posted by Prabhu on Stack Overflow See other posts from Stack Overflow or by Prabhu
Published on 2010-04-27T15:28:34Z Indexed on 2010/04/27 15:33 UTC
Read the original article Hit count: 256

Filed under:
|
|

Hello All,

Few hours back I was fiddling with a Memory Leak issue and it turned out that I really got some basic stuff about virtual destructor wrong!! Let me put explain my class design.

class Base
{
  virtual push_elements()<br>{}<br>
};

class Derived:public Base
{
vector<int> x;
public:
   void push_elements(){ 
      for(int i=0;i <5;i++)
         x.push_back(i); 
   }
};

void main()
{
    Base* b = new Derived();
    b->push_elements();
    delete b;
}


The bounds checker tool reported a memory leak in the derived class vector. And I figured out that the destructor is not virtual and the derived class destructor is not called.And it surprisingly got fixed when I made the destructor virtual. But my question is "isn't the vector deallocated automatically even if the derived class destructor is not called"? Is that a quirk in BoundsChecker tool or is my understanding of virtual destructor is wrong:)

© Stack Overflow or respective owner

Related posts about c++

Related posts about visual-c++