Destructors In C++
Destructor?
A destructor is a special member function that works just opposite to constructor which destructs or deletes an object.
➦C++ destructor is executed automatically when an object is destroyed that has been created by the constructor.
➦C++ destructors are used to de-allocate the memory that has been allocated for the object by the constructor.
When is destructor called?
➦1) The program finished execution.
➦2) When a scope (the { } parenthesis) containing local variable ends.
➦3) When you call the delete operator.
Destructor Syntax:
Class class_name {
public:
~class_name() //Destructor
{
}
}
Example :
Output :
Hey look I am in constructor function main is terminating.... Hey look I am in destructor
Parameterized Constructor
Constructors with parameters are known as Parameterized constructors. It is used to provide different values to distinct objects.
➦A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps you to assign initial value to an object at the time of its creation as shown in the following example.
Example :
Output :
Object is being created, length = 10 Length of line : 10 Length of line : 6