The destructor is a special member function whose name is same as the class name, but it is preceded by a tiled symbol(~).
For Example :-.
the destructor for the class Example will bear the name ~Example().
Definition of Destructor in C++ :-
A destructor is a member function and can be defined like any other member function. However, it doesn’t take any argument neither does it return any value.
Destructor destroys class objects created by constructor.
Note :-
Generally, A destructor should be defined under the public section of a class and it object can be destroyed in any function.
“dtor” is typical abbreviation for destructors.
following code piece outlines it
class Demo { int i, int j; ~Demo(){cout << "Destructing \n";} // private destructor . public : Demo(){i=0;j=0;} // constructor void memb1(void); void memb2(void); }; void Demo :: memb1(void) { Demo s1 ; /* valid. object can be used here.it is a member functon and thus has an access to its private destructor */ } void Demo :: memb2(void) { Demo s2 ; } void abc (void) { Demo s3; /* valid.abc is a friend function and thus has an access to sample's private members.*/ } int main() { Demo s4; /* invalid main() is a nonmember function and thus cannot access private members (destructor also as it is private). */ }
Some Characteristics of Destructors
The destructors have some special characteristics associated. These are :
- A destructor is automatically executed when object goes out of the scope.
- A destructor does not have return type and not even void.
- Destructor can be virtual, but constructors can not .
- Only one destructor can be defined in a class.
- The destructor does not have any arguments.
- An object of a class with a destructor cannot be a member of a union.
- A destructor may not be static.
- They cannot be inherited.
- Not possible to take the address of a destructor.
- Member function may be called from within a destructor.
- Destructors can’t be overloaded.