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.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.