You are on page 1of 2

CONSTRUCTOR AND DESTRUCTOR

CONSTRUCTOR - : It is the special member function of the class that is having the same name as that
of the class and this function automatically gets invoked/ called as soon as the object of the class is
created.
It is used to initialize the data member of the object of the same class as soon as the object is
created.
It is having no return type (nor even void) but the argument list, may or may not be present.
This function is declared always inside the public section of the class but can be defined within
or outside the class.

DESTRUCTOR -: It is also the also special member function of the class which is having the same as
that of the class but preceded by tilde sign ( ~ ). This function automatically gets invoked as soon as the
object of class goes out of the scope.
This function is used to free or release the memory resource utilized by the object of the class. It
can also be used to display the final values of the data members of the object of the class.
This function is not having the argument list and also no return type. It is also declared in the
public section of the class but can be defined within or outside of the class.

Q. WAP to show the working of constructor and destructor?

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

class student
{
int Roll;
float Marks;
char Name[20];
public :
student ( );
void input( );
void output( );
~ student ( );
};

void student : : input ( )


{
cout<<”\n Enter the Roll, Name And Marks :” ;
cin>> Roll>>Name>>Marks;
}
void student : : output ( )
{
cout<< “ \n Student Roll :”<<Roll <<”\t Name : “ <<Name<<”\t Marks :”<<Marks;
}

student : : student ( )
{
Roll = 123;
strcpy(Name, “Ram”);
Marks=86.5;
}

student: : ~student
{
cout<<”\n The Data”<<Roll<<” “ <<Name<<” “ <<Marks<<” are Distroyed”;
}
void main( )
{
student S;
S.output( );
S.input( );
S.output( );
getch( );
}

You might also like