on Leave a Comment

C++ Destructor concepts

Destructor is a instance member function of a class. Destructor is used to destroy the objects. The name of destructor is same as the name of class but it is preceding by tilde (~) symbol. Destructor cannot be static because is a instance member function. Destructor has no return type. Destructor never takes argument so destructor overloading is not possible. 
Destructor is usually used to deallocate memory that is allocated by constructor. 

Destructor automatically invoked when object is going to destroy.

A destructor can be defined as shown below:

~ (Class-name) ()
{  }

An example to understand destructor

#include<iostream>
using namespace std;
void test();
class number
{
    int a,b;
public:
    ~number()
    {
        cout<<"DESTRUCTOR";
    }
};
int main()
{
    test();
    return 0;
}
void test()
{
    number a;
}

OUTPUT

DESTRUCTOR

Here, when test function executes, object a of class number is  created. But when test function ends, object a also destroys, but when object a is going to destroy, destructor automatically invoked and DESTRUCTOR is printed on the screen.

Why destructor is needed?

Destructor is needed because it releases all resources allocated to an object. It is important to release resources allocated to an object because when object destroys, it is impossible to release resources allocated to that object. 

0 comments:

Post a Comment