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:
1 2 3 4 5 | class MyClass { public: int x; int y; }; |
1 2 | MyClass obj; cout << "Size of object: " << sizeof(obj) << " bytes\n"; |
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:
1 | printf("Size of int: %lu bytes\n", sizeof(int)); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; class Demo { public: int a; // 4 float b; // 4 char c; //1 }; int main() { Demo ob1, ob2; cout << "size of ob1=" << sizeof(ob1); // 9 cout << "\n size of ob2=" << sizeof(ob2); // 9 cout << "\n size of class=" << sizeof(Demo); // 9 return 0; } |
Output
1 2 3 | size of ob1=12 size of ob2=12 size of class=12 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> class Student { public: int id; char[10] name; char[10] branch; char[10] section; int semester; }; int main() { Student s; cout << "Size of object: " << sizeof(s) << " bytes" << endl; return 0; } |
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.