Memory Allocation for Object

Generally in C language, when we create a normal variable, a space is allocated to the variable to store value. The memory space is common to save and change. Only one copy of the variable is available in memory and the same copy is shared between all the functions in a program. But in case of Object in C++ language, scenario is some thing different then the normal variable declaration.

The member functions are created and placed in the memory space only once when they are defined as part of a class specification. No separate space is allocated for member functions when the objects are created.

If multiple objects of the same class type are declared then both the objects will have their own data members and separate memory space.

memory allocation for objects in c++
memory allocation for objects in c++

Only space for member variable is allocated separately for each object. A separate memory location for the objects happens, because the member variables will hold different data values for different objects.

Memory for objects is allocated when they are declared but not when class is defined. All objects in a given class uses same member functions. The member functions are created and placed in memory only once when they are defined in class definition.

Example:

class item
{
public:
int id, cost; 
void getdata();
};
int main()
{
item x,y,z;
}

In above example each object x, y and z has separate space for both id and cost. Means, value of id and cost can be different for each object. But no default space is allocated to function when object is declared. Required separate space is allocated to function during calling of that function.

Related posts