by Dinesh Thakur Category: Classes in C++

Destructors are used for reinitializing the objects which are initialized by the constructors. With the help of destructors, the objects are destroyed. This special member function is called automatically when an object is destroyed. A Destructor function also has the same name as that of the class but it is preceded by a ~, symbol.

Like constructor, a destructor can have no return type value and no declared type.

Unlike the constructor, the destructor cannot have any arguments.

Destructor plays an important role when the dynamic memory allocation technique is used. The memory space created by the new is destroyed only by the delete which is defined in the destructor.

 

e.g. ~cl(void)

{

delete variable name;

II variable name is the one which is used with 'new'

};

 

Example

 

The program illustrates the use of Constructor and Destructor.

 

 

#include <iostream.h>

#include<conio.h>

class base

{

public: int s1,s2;

public: base() { s1 =5; s2 =6;}

~base()

{

cout<<"\n invoking destructor";

}

};

void main()

{

clrscr();

base o1;

cout<<o1.s1<<" "<<o1.s2<<"\n";

}

 

Base() is the name of the constructor which is the same as that of the class. ~base() is a destructor. However, a destructor need not be explicitly invoked since it is invoked by default.

 

Output:

5 6

Invoking Destructor

Example

An example to illustrate the use of Default constructor. Employee is a class whose member data are name, age and salary. It has two member functions init() and describe()·

 

#include <iostream.h>

const int size=10;

class employee

{

public:

char name[size];

int age, salary;

char dept[size];

public: employee()

{

};

~employee()

{

}

public:

void init()

{

cout<<"enter name ";cin>>name;

cout<<"enter age ";cin>>age;

cout<<"enter department ";cin>>dept;

cout<<"enter salary ";cin>>salary;

}

void describe()

{

cout<<"\nname "<<name<<endl;

cout<<"age "<<age<<endl;

cout<<"department "<<dept<<endl;

cout<<" salary" <<salary<<endl;

}

};

int main(void)

{

employee e1;

e1.init();

e1.describe();

return 0;

}

The default constructor employee is equivalent to :

public employee()

{

strcpy(name," ");

age = 0;

strcpy(dept," ");

salary = 0;};



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article