C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Destructors in C++

Learn: What are the destructors in C++ programming language? How they declared, defined and accessed in a C++ program?

As we have discussed that a constructor is a special type of member function, which calls automatically when object is going to create.

Similarly, a destructor is a special type of member function, which called automatically when scope of an object is going to out i.e. when an object is going to be destroyed.

There are following properties of a destructor:

  • Destructor of a class has the same name as the class name.
  • It does not have a return type.
  • It does not have any argument.
  • It is preceded with the tilde character (~).
  • It cannot be overloaded.

Consider the example:

#include <iostream>
using namespace std;

class Demo
{
	private:	
		int X;

	public:
	//constructor
	Demo(int x)
	{
		X = x;
		Print();
	}
	//destructor
	~Demo()
	{
		cout<<"\nDestructor Called";
		Print();
	}

	void Print()
	{
		cout<<"\nValue of X: "<<X;
	}
};

int main()
{
    Demo OB1(10);
    Demo OB2(20);
    Demo OB3(30);

    return 0;
}

Output

Value of X: 10
Value of X: 20
Value of X: 30
Destructor Called
Value of X: 30
Destructor Called
Value of X: 20
Destructor Called
Value of X: 10

NOTE: Constructors are called in order of object declaration, and the destructors are called in the reverse order of its declaration.









COMMENTS