In C++ there is a concept of Dynamic Memory Allocation.
The concept of allocating memory during run time is called as Dynamic Memory Allocation. Here the memory allocated in Heap segment.
You can use C style “malloc ()” and “free ()” functions, but C++ provides “new” and “delete” operators.
As “new” will allocate the memory in heap, and it will return the address of the allocated memory. It is necessary to use pointer variable while using “new” operator.
Below are few points on new and delete operators.
1. “new” operator is used to allocate memory and also to create an object for a class.
2. “new” operator will allocate memory from the heap.
3. The memory allocated by using “new” operator should be deleted by “delete” operator.
4. “delete” operator will destroy the object and releases the heap memory.
5. Don’t mix C memory allocation functions like malloc(), calloc() or free() with “new” and “delete” operator.
Example 1:
Simple example for new and delete operator in C++
#include <iostream>
// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;
int main()
{
int *ptr;
ptr = new int[3];
*ptr = 10;
*(ptr + 1) = 20;
*(ptr + 2) = 30;
for(int i = 0; i< 3 ; i++)
{
cout<<*(ptr+i)<<endl;
}
delete []ptr;
}
Output:
10
20
30
Example 2:
Example to show that the destructor will not be called automatically when you allocate the object using “new”.
#include <iostream>
// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;
class MyClass
{
int i;
public:
MyClass()
{
cout<<"Constructor"<<endl;
}
~MyClass()
{
cout<<"Destructor"<<endl;
}
};
int main()
{
MyClass *ptr = new MyClass();
}
Output:
Constructor
In the above example, we see that, only constructor is called. But destructor is not called. Hence when you create an object using constructor, we need to destroy that object using destructor.
In the below example, we destroy the object using destructor.
#include <iostream>
// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;
class MyClass
{
int i;
public:
MyClass()
{
cout<<"Constructor"<<endl;
}
~MyClass()
{
cout<<"Destructor"<<endl;
}
};
int main()
{
MyClass *ptr = new MyClass();
delete ptr;
}
Output:
Constructor
Destructor
When we give “delete ptr“, it will not delete the pointer. It will delete the object pointed by pointer.