Object Oriented Programming -
Dynamic Memory Allocation to
Objects
Dynamic Memory Allocation
• Every program needs storage to be allocated to it for various
purposes.
• When you write a program, you specify what storage it needs by
declaring variables and instances of classes, e.g:
int a,b,c;
float nums[100];
Circle myCircle(2.0,3,3); etc...
• Then when the program executes, it can make use of this memory
• It is not possible for variables or objects to be added during the
execution of a program
Programs & Memory
• To execute a program, it must be loaded into RAM (Random Access
Memory)
• Program loaded into main memory is divided into 4 segments:
• Code
• Data
• Stack
• Heap
• Data Segment: contains the global variables and static variables.
• Code Segment: contains the executable instruction
• Stack Segment: Store all auto variables e.g. Function parameters, Return
address
Programs & Memory (cont.)
• Heap Segment: It is for dynamic memory allocation
• Allocates memory for its requirement and delete memory after it is no longer needed.
• Dynamically allocate array size.
• Keywords: new and delete
• Example:
int *ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated memory
delete ptr;
int *p;
p = new int[10];//allocating dynamic array
delete [] p;
Example
int main() {
int *ptr; //Pointer that can point to an integer
ptr = new int(87);//Allocate memory and initialize to 87
if(!ptr) //NULL pointer returned
{
cout << "Allocation error\n";
}
else
{
cout <<"Memory location: "<< ptr;
cout <<" contains the int value: "<< *ptr <<endl;
delete ptr; //deallocate the memory
}
return 0;
}
Example
int main() {
int *ptr; // Pointer that can point to an integer
int size = 5; // Size of the array
ptr = new int[size]; // Allocate memory for an array of size 5
if (!ptr) // NULL pointer returned
{
cout << "Allocation error\n";
} else {
cout << "Memory location: " << ptr << " contains the following values: ";
for (int i = 0; i < size; ++i) {
ptr[i] = i + 1; // Initializing array elements with some values
cout << “\n “<< ptr[i] << " ";
}
cout << endl;
delete[] ptr; // Deallocate the memory
}
return 0; }
Array of Object
• The Array of Objects stores objects. An array of a class type is also
known as an array of objects.
• Syntax:
ClassName ObjectName[number of objects];
• Example:
Employee e[50];
Array of Object
Output
Array of Object
• Other way for array of object with similar output
Array of Object
Output
Dynamically Allocate Array of Object
Output
Dynamically Allocate Array of Object
Output