Q:

How does the c++ sizeof operator calculate size?

I created a class X having only 2 public functions (constructor and destructor), and using sizeof operator the class size is coming to be 1.
When I add a private data member of type char to the above class declaration, the size is still 1.
Finally I add an integer type to it as a class data member, and now the size is 8 bytes.
Kindly explain to me the how a class size is calculated.

A:

First, realise that functions that are not virtual have no effect on the size of a class.
The size of an instance of any class is at least 1 byte, even if the class is empty, so that different objects will have different addresses.
Adding a char ensures that different objects will have different addresses, so the compiler doesn't artificially add one to the size. The size is then sizeof(char) = 1.
Then you add an int, which (probably) adds 4 bytes on your platform. The compiler then decides to pad the class so it will be aligned for performance/CPU-requirements reasons, and adds 3 empty bytes so that the size is now 1 + 3 + 4 = 8. It probably adds the padding before the int member so that it will be aligned on a 4 byte boundary, but it's not required to unless your CPU requires it.
You can read about padding on the Wikipedia page.

A:

There are many factors that decide the size of an object of a class in C++. These factors are:

Size of all non-static data members
Order of data members
Byte alignment or byte padding
Size of its immediate base class
The existence of virtual function(s) (Dynamic polymorphism using virtual functions).
Compiler being used
Mode of inheritance (virtual inheritance)

You can find more here http://www.cprogramming.com/tutorial/size_of_class_object.html

