Size of the Object in C++

In a C++ programming language, the size of any object is equal to the sum of the size of all the class data members.

In C++, the sizeof the operator returns the size of an object in bytes, including any padding added for alignment. The size of an object is determined by the sum of the sizes of its data members, with any additional padding required for alignment.

For example, if we have a class MyClass with two int members:

This would output the size of the obj object in bytes. Note that the size of an object may be larger than the sum of its data members if additional padding is required for alignment.

In C, the sizeof the operator works in a similar way to C++. However, C does not have classes, so the sizeof operator is used with data types instead. For example, to find the size of an int in C:

Another example of class contains three data type and three variable. 

Data type int occupies 4 bytes, float occupies 4 bytes, and char occupies 1 byte. their sum is  9 bytes.

In this program size of an individual of object is 9 bytes. We can know the size of an object/class by using  sizeof() operator.


In this code, we define the Student class with five fields: id of type int, name, branch, and section of type char[20], and semester of type int. We then create an object of the Student class called s in the main() function.

To find the size of the Student object, we use the sizeof operator, which returns the size of an object in bytes. We then output the size of the Student object to the console using cout. The output should be something like:

Size of object: 32 bytes

the size of an object of a class may vary depending on the data types.

Categories C++