Destructors

Destructors

Destructor is another special member function that is called by the compiler when the scope of the object ends.

// C++ program to explain destructors

#include <iostream>
using namespace std;
class prog
{
public:
int id;

//Definition for Destructor
~prog()
{
cout << “Destructor called for id: ” << id <<endl;
}
};

int main()
{
prog obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
prog obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here
scope
return 0;
} // Scope for obj1 ends here

Output:

Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7

error: Content is protected !!