thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2281

Memory management with and without the virtual destructor

Why virtual destructor makes these differeces in the memory management?

I have a class:

class A
{
public:
    A() : m_x(0) { }
    ~A() {}
public:
    static ptrdiff_t member_offset(const A &a)
    {
        const char *p = reinterpret_cast<const char*>(&a);
        const char *q = reinterpret_cast<const char*>(&a.m_x);

        std::cout << "\n&a   =" << &a << "\n&a.mx=" << &a.m_x << "\np=" << (int)p << " q=" << (int)q << '\n';

        return q - p;
    }
private:
    int m_x;
};

and if I call the A a; member_offset(a); I get printed:

&a   =002EFD28
&a.mx=002EFD28
p=3079464 q=3079464

an if I make the destructor virtual, I am getting other addresses:

&a   =002EFD28
&a.mx=002EFD2C
p=3079464 q=3079468

Why? What influence has virtual destructor on memory management?

Upvotes: 1

Views: 105

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

With no virtual functions (and meeting various other constraints), the class has standard layout, and its first data member is guaranteed to have the same address as the object itself.

With one or more virtual functions, it is polymorphic and no longer has standard layout, and there is no such guarantee. Typically, polymorphism is implemented by adding a hidden pointer (sometimes known as the virtual pointer or vptr) to the class, pointing to the class-specific virtual function table (sometimes known as the vtable) and other dynamic type information. In this case, it looks like this pointer comes before the declared members, leading to the difference in addresses that you observe.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258618

A virtual method table pointer is added to each instance of the class - typically at the beginning of the object. It doesn't have to be a destructor, any first virtual method will determine the generation of a virtual method table.

Upvotes: 6

Related Questions