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.
#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; }
Total : 30 Memory DestroyedTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions