Ishita
Ishita

Reputation: 489

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.

Upvotes: 14

Views: 2099

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75130

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.

Upvotes: 24

psu
psu

Reputation: 379

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

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

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

Upvotes: 8

Related Questions