Destructor Overloading in C++ Programming


A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ) . The destructor is the last function that is going to be called before an object is destroyed.

Syntax :
   ~ class_Name ( ) { }

Example :
   ~ student ( ) { }

In this program, a class named math is defined with three private member variables: a, b, and c. The class has a constructor math() which initializes the values of a and b to 10 and 20 respectively. The class also has a member function add() which adds the values of a and b and stores the result in c, and then prints the value of c.

The most important part of this program is the destructor function ~math(). The destructor function has a special syntax that starts with a tilde (~) followed by the name of the class. The destructor function is automatically called when an object of the class is destroyed. In this program, the destructor function simply prints the message "Memory Destroyed" before the object is destroyed.

In the main() function, an object o of the class math is created. Then the add() function of the object o is called, which calculates and prints the sum of a and b. Finally, the program returns 0, which indicates successful completion of the program.

Source Code

#include<iostream>
using namespace std;
//Destructor in C++ Programming
 
/*
Destructor is an instance member function which is invoked automatically
whenever an object is going to destroy.
Means, a destructor is the last function that is going to be
called before an object is destroyed.
*/
 
class math
{
private:
    int a,b,c;
public:
    math()
    {
        a=10;
        b=20;
    }
    ~math()
    {
        cout<<"Memory Destroyed";
    }
    void add()
    {
        c=a+b;
        cout<<"Total : "<<c<<endl;
    }
};
 
int main()
{
    math o;
    o.add();
    return 0;
}
 
 

Output

Total : 30
Memory Destroyed
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples