Constructor and Destructor
What is the need of a constructor and it can be explained with an example:
// Turbo C compiler
#inlcude
#include
#include
class Stud
{
int Rno;
char Name[10];
public:
void Input()
{
cout<<"Enter Roll number:";
cin>>Rno;
cout<<"Enter name :";
gets(name);
}
void Output()
{
cout<<"\nEntered Roll number:"<<Rno;
cout<<"\nEntered name :";
puts(name);
}
};
void main()
{
Stud S;
S.Output();
}
/* When Program is compiled the output will be a garbage value and now let us see how constructor is useful in this situation. The above will now include a constructor and destructor
*/
#inlcude
#include
#include
#include
class Stud
{
int Rno;
char Name[10];
public:
Stud() // constructor
{
Rno=5;
strcpy(Name,"Rahul");
}
void Input()
{
cout<<"Enter Roll number:";
cin>>Rno;
cout<<"Enter name :";
gets(name);
}
void Output()
{
cout<<"\nEntered Roll number:"<<Rno;
cout<<"\nEntered name :";
puts(name);
}
~Stud() //destructor
{cout<<"Object destructed";}
};
void main()
{ //line 1
Stud S; //line 2
S.Output();
}//last line
/* Now When program is compiled at line 2 constructor is automaticaly called and initializes the value for its datamember we will get the output as
Entered Roll number: 5
Entered name : Rahul
and when the program ends i.e last line destructor will be called automatically */
/*If any doubt regarding the above code can be cleared by asking questions and in the next session I will explain all types of constructor*/