Destructors in C++


Destructors

  • Destructors are used to deallocate the memory.
  • These are used to destroy the objects created or initialized by constructor when
    they are no longer required.
  • These also have the same name as that of class.
  • It is preceded by ~(tilde) symbol.

Syntax :

~constructor-name();

Example :

#include <iostream.h>
#include <conio.h>


class Account
{
private:

int account_no;
int balance;

public :

Account(int a,int b)
{
account_no=a;
balance=b;
}

void display()
{
cout<< "Account number is : "<< account_no;
cout<< "\nBalance is : " << balance;
}

~Account() //destructor defined
{

}

};

void main()
{
clrscr();

Account acc(121,5000);
acc.display();

getch();
}

Output :








Properties of destructors :

  • Destructor is invoked automatically when the objects are destroyed.
  • It can't have any argument.
  • It has same name as of constructor or class.
  • It may not be static.
  • It can't be inherited.
  • We can take the address of a destructor.

0 comments:

Post a Comment