Monday, April 7, 2014

Size of an empty object in C++

What is the size of an empty object in C++?
This is one of the most frequently asked questions on forums.

For example consider the following code snippet.

class A
{
};

A aOb;
cout << sizeof(aOb);

The size of an empty object is not zero to ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects.

On most of the compilers, it would return 1 byte. Even if the class contains only member functions and no data members, this is applicable.

However if the class contains at least one virtual method, the sizeof() operator returns 4 bytes on a typical compiler. This is so because every class with at least one virtual function has a pointer to vtable stored which is helpful in dynamic binding.

class B
{
   virtual void func()
   {
   }
};

B b;
cout << sizeof(b);