Destructor

 

Destructor:

A destructor is a special member function used to destroy the objects of class

Syntax:

class classname

{

            private:

                        ---------

            pubic:

                        classname(argument list)

                        {

                                    ------------

                        }

                        ~classname()

                        {

                                    ------------

                        }

 

};

 

Characteristics of destructors:

1.    Name of the destructor is same as class.

2.    The first character must be ~(tilde).

3.    Cannot take any arguments.

4.    Cannot be overloaded.

5.    There is no return type.

6.    Destructor should be declared in the public section.

7.    A class can have only one destructor.

8.    Used to de-allocate the memory of the object.

 

Ex:

#include<iostream.h>

#include<conio.h>

class number

{

            private:

                        int data;

            public:

                        number()

                        {

                                    cout<<”constructor is invoked\n”;

                                    data=10;

                        }

                        ~number()

                        {

                                    cout<<”destructor”;

                        }

                        void display()

                        {

                                    cout<<”data =”<<data;

                        }

};

void main()

{

            number n;

            clrscr();

            n.display();

            getch();

}

Comments