Classes, Objects, and Memory
Objects are the identifiers declared for class data type. Object is a composition of one more variables declared inside the class. Each object has its own copy of public and private data members. An object can access to its own copy of data members and have no access to data members of other objects.
Only declaration of a class does not allocate memory to the class data members. When an object is declared, memory is reserved for only data member and not for member functions.
Consider the following program.
8.12 Write a program to declare objects and display their contents.
Explanation: M1 and M3 are objects of class month. Separate memory is allocated to each object. The contents and address of the member variables are displayed in the output. Figure shows it more visibly.
Memory occupied by objects
From the last program it is clear that memory is allocated for data members. What about functions? Member functions are created and memory is allocated to them only once when a class is declared. All objects of a class access the same memory location where member functions are stored. Hence, separate copies of member functions are not present in every object like member variables, which is illustrated in the following program and Figure.
8.13 Write a program to display the size of the objects.
Explanation: In the above program, the class data has three member variables of long, float, and char type. The d1 and d2 are objects of the class data. The sizeof operator displays the size of objects. The size of any object is equal to the sum of sizes of all the data members of the class. In the class data, the data type long occupies 4 bytes, float occupies 4 bytes, and char occupies 1 byte. Their sum is 9, which equals the size of an individual object.
The member functions are not considered in the size of the object. All the objects of a class use the same member functions. Only one copy of member function is created and stored in the memory whereas each object has its own set of data members.
Data members and member functions in memory