1

Possible Duplicate:
When to use virtual destructors?

let's say i have an abstract class Animal

class Animal {
public:
    Animal(const std::string &name) : _name(name)
    {
    }
    virtual void Print() const = 0;
    virtual ~Animal() {}
protected:
    std::string _name;
};

and i have Dog and Cat that inherit this class. In a book i'm reading it is recommended to define a virtual destructor in base-class. I tried to create objects without the definition of virtual des' and the program runs fine, without leaks (checked with valgrind). So my question is why use virtual destructor (with empty implementation)? what is the benefit from it?

thank you!

Community
  • 1
  • 1
Asher Saban
  • 4,343
  • 12
  • 43
  • 54
  • 1
    Possible duplicate of [When to use virtual destructors?](http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – James McNellis Sep 19 '10 at 18:03

1 Answers1

1

When you have something like this:

class Dog : public Animal {
public:
   Dog() {
      data = new char[100000];
   }
   ~Dog() {
       delete data;
   }
private:
   char* data;
};

Animal* dog = new Dog;
delete dog;

Without virtual destructor, compiler use destructor from Animal class. And memory allocated in Dog class will leak. When you define virtual destructor in base class, compiler use destructor from Dog class and free allocated memory.

ldanko
  • 487
  • 7
  • 17