6/19/08

What is the size of an Empty Class, Class with virtual functions and class with only normal functions, no data members?

Size of an Empty Class.

class MyClass {
};

MyClass myObject;
sizeof(myObject);

The size of an empty class is 1 byte.
Since size of class is calculated as the size of data members it contains.
Since empty class doesnt contains any data member, its size is zero. but to keep the existence on object in memory size of empty class object is 1 byte.

Size of Class with virtual functions

class MyClass {

public:
virtual void myfunct();
};

MyClass myObject;
sizeof(myObject);


This will be 4 bytes. as this object will contain VPTR pointer to virtual table.
As it has some size compile doesnt add one byte which it adds to the empty class.


Size of class with only normal functions, no data members?


class MyClass {

public:
void myfunct();
};

MyClass myObject;
sizeof(myObject);


This will again 1 byte as it has no data members.
Class size is comprised of only data members and not member functions.

1 comment:

Anonymous said...

good explaination !

http://www.itucu.com/2010/09/what-is-the-size-of-an-object-of-a-empty-c-class/