Search code examples
c++heap-memoryvirtual-destructor

Virtual destructor and memory deallocation


I'm not quite sure I understand virtual destructors and the concept of allocating space on the heap right. Let's look at the following example:

class Base
{
public:
    int a;
};

class Derived : public Base
{
public:
    int b;
};

I imagine that if I do something like this

Base *o = new Derived;

that 8 Bytes (or whatever two integers need on the system) are allocated on the heap, which looks then something like this: ... | a | b | ...

Now if I do this:

delete o;

How does 'delete' know, which type o is in reality in order to remove everything from the heap? I'd imagine that it has to assume that it is of type Base and therefore only deletes a from the heap (since it can't be sure whether b belongs to the object o): ... | b | ...

b would then remain on the heap and be unaccessible.

Does the following:

Base *o = new Derived;
delete o;

truly provoke memory leaks and do I need a virtual destructor here? Or does delete know that o is actually of the Derived class, not of the Base class? And if so, how does that work?

Thanks guys. :)


Solution

  • You're making a lot of assumptions about the implementation, which may or may not hold. In a delete expression, the dynamic type must be the same as the static type, unless the static type has a virtual destructor. Otherwise, it is undefined behavior. Period. That's really all you have to know—I've used with implementations where it would crash otherwise, at least in certain cases; and I've used implementations where doing this would corrupt the free space arena, so that the code would crash sometime later, in a totally unrelated piece of code. (For the record, VC++ and g++ both fall in the second case, at least when compiled with the usual options for released code.)