Вы находитесь на странице: 1из 2

DESTRUCTOR Definition: A destructor is a special member function.

on. Destructor is used to destroy the objects that have been created by a constructor. Like a constructor, destructor is member function whose name is the same as the class name but is preceded by a tide (~). It is invoked automatically to reclaim all the resources allocated to the object when the object goes out of scope and is no longer needed.

Destructor(Inside Class) Syntax: class classname { public: ~classname( ) { //destructor body } }; Example #include<iostream.h> #include<conio.h> int count=0; class des { public: des() { count++; cout<<Number of object created<<count<<endl; } ~des() { cout<<Number of object destroyed<<count<<endl; } }; void main() { cout<<Enter Main<<endl;
Page 1 of 2

des ob1,ob2,ob3,ob4; { cout<<Enter block1<<endl; des ob5; } { cout<<Enter block2<<endl; des ob6; } cout<<Re-entermain<<endl; } Output: Enter Main Number of object created 1 Number of object created 2 Number of object created 3 Number of object created 4 Enter block1 Number of object created 5 Number of object destroyed 5 Enter block2 Number of object created 5 Number of object destroyed 5 Re-enter Main Number of object destroyed 4 Number of object destroyed 3 Number of object destroyed 2 Number of object destroyed 1 Characteristics of Destructor: - A class cannot have more than one destructor. - A destructor must be declared in the public section of a class so that it is accessible to all its users. - It has no return type.

Page 2 of 2

Вам также может понравиться