Our social:

Tuesday, October 4, 2016

Destructor in C++ Tutorial


Destructor is a special member function that always executes when compiler is destroying an object. It is used to free allocated memory, close and dispose used resources and for any other things which we want to execute before destroy an object.
The name of the destructor starts with tilde (~) followed by the name of the class. Destructor does not have any parameters. Here is an example of a destructor for person class:
 cout << "Destructor called for " << firstName << " object" << endl;
During this topic, we created three objects:
Person person1;//declare a person
//use constructor with 3 parameters
Person person2("Smith", "James", 1992);

Person person3("Green", "Alan");
Execute this program. Destructor will be called for all the created objects:
Default constructor is starting
Constructor with 3 parameters is starting
First name Smith
Last name James
Year of Birth 1992
Constructor with 3 parameters is starting
First name Green
Last name Alan
Year of Birth 1990
Destructor called for Green object
Destructor called for Smith object
Destructor called for  object
Last line “Destructor called for object” do not specify any name, because person1 was created by using default constructor. As you can see, destructors are called in back order relatively to the order of objects created. The first created object is destroyed last. And the last created object is destroyed first.


Post a Comment

Hello Every One thanks For Visit My site You Can Suggest any Idea About site And Related Education Information Provide me Its Best Content For you am Include in this Site And feel free contact And email now I hope This site very help full you