开发者

why use virtual destructor in inheritance [duplicate]

This question already has answers here: Closed 12 years ago.

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜