Destructors are the inverse functions of constructors. They are called when the object is destroyed (disposed). ~Specify the function as a destructor for the class by placing a tilde () in front of the class name.
declaring destructors
A destructor has the same name as the class, but preceded by a tilde character (
~) of the function
The first form of the syntax is used for destructors declared or defined in a class declaration, and the second form is used for destructors defined outside the class declaration.
Multiple rules manage the declaration of a destructor. Destructors:
Parameters are not accepted.
You cannot specify any return type (including void ).
You cannot use a return statement to return a value.
cannot be declared as const, volatile or static. However, they can be called for destruction of objects declared as const, volatile or static.
Can be declared as virtual. By using a virtual destructor, you can destroy an object without knowing the type of the object-the correct destructor for the object is invoked using a virtual function mechanism. Note that destructors can also be declared as pure virtual functions of abstract classes.
using Constructors
The destructor is called when one of the following events occurs:
Use the delete operator to explicitly deallocate an object that is assigned using the new operator. When you deallocate an object by using the delete operator, the memory is freed for most derived objects or for objects that belong to the full object, but not the child objects of the base class. This "most derived object" deallocation must be valid only for virtual destructors. In multiple inheritance cases where the type information does not match the underlying type of the actual object, the deallocation may fail.
A local (Automatic) object with a block range is out of range.
The lifetime of the temporary object ends.
The program ends, and there are global or static objects.
The destructor is explicitly called with the fully qualified name of the destructor. (For more information, see explicit destructor calls.) )
Example
//operator Delete[] Example#include <iostream>//Std::coutstructMyClass {MyClass () {std::cout<<"MyClass constructed\n";} ~myclass () {std::cout <<"MyClass destroyed\n";}};intMain () {MyClass*pt; PT=Newmyclass[3]; Delete[] PT; return 0;}
Output:
MyClass Constructedmyclass Constructedmyclass constructedmyclass destroyedmyclass Destroyedmyclass destroyed
"C + + Note" destructor (destructor)