Destructor in C++





"Destructor" functions are the inverse of constructor functions.

A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer type object of that class.

Declaring Destructor :
  • A destructor's name will same as class name preceding by tilde (~) sign.

  • Destructor does not have any return type like constructor and never takes any parameter.

  • Destructor cannot be overload.

  • Can be declared as virtual. Using virtual destructors, you can destroy objects without knowing their type — the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes.

Example:
class Test {
public:
Test( ){
cout<<"CONSTRUCTOR CALLED"<< endl;
//CODE FOR DATA MEMBER AT OBJECT CONSTRUCTION TIME
}
~Test( ){
cout<<"DESTRUCTOR CALLED"<< endl;
//CODE FOR CLEAR DATA AT OBJECT DESTRUCTION TIME
}
};                            
                        
Program to understand the execution of destructor:
#include<iostream>
using namespace std;
class Test {
public:
Test( ){
cout<<"CONSTRUCTOR CALLED"<< endl;
}
~Test( ){
cout<<"DESTRUCTOR CALLED"<< endl;
}
};   
int main(){
//constructor called
Test ob;
int a = 1;
if(a)
 {
  //constructor called
   Test obj;
  cout<<"a = "<< a<< endl;
 }
//scope of 'obj' finish 
//destructor called for obj
}
//scope of 'ob' finish 
//destructor called for ob
OUTPUT:
CONSTRUCTOR CALLED
CONSTRUCTOR CALLED
a = 1;
DESTRUCTOR CALLED
DESTRUCTOR CALLED

Next topic is Encapsulation





 




Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved