Possible Duplicate:
When to use virtual destructors?

I've got a question towards the destructor in c++. How's the compiler during these 3 situation working:

basically have non own destructor

basically have my very own destructor

if I've got a virtual destructor

I understand if there's no destructor produced by the programmer, the compiler can create one. But what's the distinction between both of these? And it is the compiler faster basically have always my very own destuctor?

After which virtual. Where must we use virtual destructors and where not?

If you do not define a destructor, the compiler can create choice for you, equal to:

~T() {}

Which means you should write your personal destructor if you want to do a lot more than the default.

You must declare an online destructor if you're invoking delete on derived objects using a pointer to base class. e.g.:

class Base {
public:
    virtual ~Base() {}  // MUST be virtual
};

class Derived : Base {
};

Base *p = new Derived;
delete p;  // Would be undefined behaviour unless ~Base is virtual

Discover using inheritance (or maybe you are never doing something similar to the above mentioned), then you definitely don't need to make use of virtual destructors. In some instances, this leads to slightly faster code. But oftentimes, it will not make a difference.

The compiler-produced default destructor will basically do nothing at all. All people of the class is going to be destructed once the class is destructed, but after the destructor (just like all people are built once the class is built. Hence the initialization list that's before the constructors).

You need to only write a destructor if you want special handling for many people. For instance, naked pointers that should be deleted, as well as other resource that should be completed if this class is destroyed.

An online destructor is available to ensure that this can be done:

Base *base = new Derived();
delete base;

When the destructor of Base is non-virtual, then ~Base() is going to be known as by delete. This really is BAD, because base isn't really a Base it's a Derived. What you would like is perfect for ~Derived() to become known as, even when the pointer just is surely a Base during the time of deletion. Therefore, you are making the destructor of Base virtual.

well for those who have your personal destructor the compiler should'nt work fast because it needs to review your instructions(compile and execute them). you'll need your personal destructor if you need to not only free memory on object destruction but make a move other too(like logging). You might need a virtual destructor in the event when you're using virtual functions(not neccessary)