Deletion of array of objects in C++
Need for deletion of the object:
- To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section.
- If objects are not deleted explicitly then the program will crash during runtime.
Program 1: Create an object of the class which is created dynamically using the new operator and deleting it explicitly using the delete operator:
C++
#include <iostream>
using namespace std;
class Student {
public :
Student()
{
cout << "Constructor is called!\n" ;
}
~Student()
{
cout << "Destructor is called!\n" ;
}
void write()
{
cout << "Writing!\n" ;
}
};
int main()
{
Student* student = new Student();
student->write();
delete student;
return 0;
}
|
Output:
Constructor is called!
Writing!
Destructor is called!
Program 2: Create an array of objects using the new operator dynamically. Whenever an array of the object of a class is created at runtime then it is the programmer’s responsibility to delete it and avoid a memory leak:
C++
#include <iostream>
using namespace std;
class Student {
public :
Student()
{
cout << "Constructor is called!\n" ;
}
~Student()
{
cout << "Destructor is called!\n" ;
}
void write()
{
cout << "Writing!\n" ;
}
};
int main()
{
Student* student = new Student[3];
student[0].write();
student[1].write();
student[2].write();
delete [] student;
return 0;
}
|
Output:
Constructor is called!
Constructor is called!
Constructor is called!
Writing!
Writing!
Writing!
Destructor is called!
Destructor is called!
Destructor is called!
Program 3:
Below is the program where delete is used to delete an array of objects:
C++
#include <iostream>
using namespace std;
class Student {
public :
Student()
{
cout << "Constructor is called!\n" ;
}
~Student()
{
cout << "Destructor is called!\n" ;
}
void write()
{
cout << "Writing!\n" ;
}
};
int main()
{
Student* student = new Student[3];
student[0].write();
student[1].write();
student[2].write();
delete student;
return 0;
}
|
Explanation: This program will crash in runtime. In this program, constructors are working properly but the destructor is executed only for the first object, and after that program is crashing at runtime because of a memory leak. It is because 3 objects are created at runtime but only one object is deleted explicitly and that’s why the remaining two objects are crashing at runtime.
Conclusion:
In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.
Last Updated :
18 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...