Dynamic Allocation in C++
C++ provides allocation and deallocation functions ‘new’ and ‘delete’ similar to the malloc() and free() function in C. The main advantage of dynamic allocation is that it allows us to automatically allocate enough memory to hold an object of the specified type and you don’t need to use the ‘sizeof’ operator. Also, you don’t need to explicitly type cast as when allocating memory using malloc(). Both new delete can be over-loaded to create customized allocation systems.
Simple C++ program showing dynamically allocating variable and returning the address of allocation
main(){
int *p;
p = new int(100); // or *p = 100
if(!p){
cout << "Allocation error\n";
exit(1);
}
cout << "\nAt " << p << " is " << *p;
delete p;
return 0;
}
Output:
At 0x2321c20 is 100
Simple C++ program showing dynamically allocating an array and returning the address of allocation
main(){
int *p, i;
p = new int[10]; // or *p = 100
for(i=0; i < 10; i++){
p[i] = i;
}
for(i=0; i < 10; i++){
cout << "At " << &p[i] << " is : " << p[i] << "\n";
}
return 0;
}
Output:
At 0x12dec20 is : 0
At 0x12dec24 is : 1
At 0x12dec28 is : 2
At 0x12dec2c is : 3
At 0x12dec30 is : 4
At 0x12dec34 is : 5
At 0x12dec38 is : 6
At 0x12dec3c is : 7
At 0x12dec40 is : 8
At 0x12dec44 is : 9
Simple C++ program showing dynamically allocating objects
class sum{
int a,b;
public:
sum(int i, int j) { a=i, b=j; }
void find_sum(){
cout << a + b;
}
};
main(){
sum *p;
p = new sum(2,3);
p->find_sum();
delete p;
return 0;
}
Output:
5
Simple C++ program showing dynamically allocating array of objects
#include <iostream>
using namespace std;
class sum{
int a,b;
public:
sum(int i, int j) { a=i, b=j; }
sum();//parameterless constructor function
void find_sum(){
cout << a + b;
}
};
main(){
sum *p;
//array of object
p = new sum[2]; // const func cannot be initialized
p[0].sum(2,3);
p[1].sum(3,4);
p[0].find_sum();
p[1].find_sum();
return 0;
}