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.
It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.
The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
Need of sizeof() operator Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator: int *ptr=malloc(10*sizeof(int));
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.
There are many factors that decide the size of an object of a class in C++. These factors are:
You can find more here http://www.cprogramming.com/tutorial/size_of_class_object.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With