0
votes

I have following base class, and i checked the size of this class, it shows 16 byte. If I remove the virtual keyword from fun(), then it shows 4 byte.

I don't understand this behavior. any pointers?

class base
{
        public :
        int a;
        virtual void fun()
        {
        }
};

gcc version: gcc version 4.1.2 20080704

OS : Linux 2.6.18-308.el5 #1 SMP Fri Jan 27 17:17:51 EST 2012 x86_64 x86_64 x86_64 GNU/Linux

3

3 Answers

7
votes

Your compiler apparently stores a pointer inside each instance to support the virtual dispatch machinery (this is very common, it's called a v-table pointer). Since you're on a 64-bit architecture, that both adds 8 bytes to the size of the class, and also makes the alignment 8 bytes. The size always has to be a multiple of the alignment in order to make alignment of array elements work, so there will be 4 bytes of padding for alignment reasons, for a total of 16.

1
votes

To implement polymorphic behaviour for virtual methods or virtual base class during run time, compiler implementions add certain hidden members. This is compiler and platform specific behaviour. The size of any polymorphic class can vary across different implementations of the compiler.

This makes C++ object memory model non-compatible with C memory model.

0
votes

Well "any pointers" is actually the right guess. Every polymorphic class stores some additional "hidden" information in addition to explicitly declared data fields. In a typical implementation it will store a pointer to so called Virtual Method Table (VMT). The size of that pointer is exactly what contributes extra bytes to the size of the class in your case.

Apparently you are compiling your code on a 64-but platform, which uses 8-byte pointers. So the total size of your class is 8 for VMT pointer, 4 for your int a field and 4 more padding bytes to align the class size to 8-byte boundary. If you compile your code in 32-bit mode, the sizeof for this class will probably evaluate to 8.

In single-inheritance hierarchy all classes will typically "share" the pointer introduced by the topmost polymorphic class in the hierarchy, meaning that the size of any polymorphic class grows by size of a single pointer. But in multiple-inheritance hierarchy it is possible to end up with multiple hidden VMT pointers inside a single class, meaning that the size of such class will grow by size of a multiple pointers.