-->

Friday, 14 July 2017

C++ Destructor Basics

C++ Destructor Basics




Image result for destructor logo
  1. Destructors are special member functions of the class required to free the memory of the object whenever it goes out of scope.
  2. Destructors are parameterless functions.
  3. Name of the Destructor should be exactly same as that of name of the class. But preceded by ‘~’ (tilde).
  4. Destructors does not have any return type. Not even void.
  5. 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.

keep calm and say bujuku bujuku.

0 comments:

Post a Comment

Start Work With Me

Contact Us
KUTTY SELVA
+91 7708139984
Madurai,Tamilnadu