C++ Destructor Basics
C++ Destructor Basics
- Destructors are special member functions of the class required to free the memory of the object whenever it goes out of scope.
- Destructors are parameterless functions.
- Name of the Destructor should be exactly same as that of name of the class. But preceded by ‘~’ (tilde).
- Destructors does not have any return type. Not even
void.
- The Destructor of class is automatically called when object goes out of scope.
C++ Destructor programs
C++ Destructor Program #1 : Simple Example
#include<iostream> using namespace std; class Marks { public: int maths; int science; //constructor Marks() { cout << "Inside Constructor"<<endl; cout << "C++ Object created"<<endl; } //Destructor ~Marks() { cout << "Inside Destructor"<<endl; cout << "C++ Object destructed"<<endl; } }; int main( ) { Marks m1; Marks m2; return 0; }
Output
Inside Constructor C++ Object created Inside Constructor C++ Object created Inside Destructor C++ Object destructed Inside Destructor C++ Object destructed
Explanation :
You can see destructor gets called just before the return statement of main function. You can see destructor code below –
~Marks() { cout << "Inside Destructor"<<endl; cout << "C++ Object destructed"<<endl; }
C++ Destructor always have same name as that of constructor but it just identified by tilde (~) symbol before constructor name.
0 comments:
Post a Comment