Destructor In C++

 Destructor In C++




What is Destructor in C++:

A destructor is a special member function which is automatically invoked when an object is destroyed. Destructor gets executed when an instance of the class goes out of existence.

Its primary usage is to release space on the heap.  A destructor function may be invoked explicitly. It is used basically deallocate memory .

Following are some rules for writing destructor function,

The destructor function is same as that of the class from which it belongs

With the class one another special character is (~) tilde.

It is declared with no return type not even void. It cannot return value.

It cannot be declared static, const or volatile

It takes no argument hence it cannot be overloaded

It should have public access in class declaration


General Syntax to declare destructor:

class class_name

{

private:

//data variable

protected:

//data

public:

class_name(); //constructor

~class_name(); //destructor

};


Following example illustrate the destructor function ,

class employee

{

private:

char name[20];

int id;

public:

employee(); //constructor

~employee(); //destructor

void display();

};


C++ program to demonstrate destructor. 


#include<iostream.h>

#include<conio.h>

class employee

{

private:

char name[20];

public:

employee(); //constructor

~employee(); //destructor

void display();

}; //end of class definition

employee::employee() //constructor

{

cout<<”Enter name of Employee”<<endl;

cin>>name;

}

employee::~employee() //destructor

{

cout<<”Data has been cleaned”<<endl;

}

void employee::display()

{

cout<<”The name of employee is”<<endl;

cout<<name;

}

void main()

{

employee obj;

obj.display();

}


टिप्पणी पोस्ट करा

0 टिप्पण्या