Constructor overloading
Parameterized constructor
Constructors that take arguments are called as parameterized constructor.
Constructor overloading:
*It is possible to overload a class’s constructor function. i.e., More than one constructors declared with in a single class.
*Reasons to overload constructor function:
1.To gain flexibility
2.To support arrays
3.To create copy constructor
Program:
#include<iostream.h>
class Time
{
int Hr,Min;
public:
Time() //No Argument Constructor(default)
{
Hr=0;
Min=0;
}
Time(int H,int M) //Two Argument(int type) Constructor
{
Hr=H;
Min=M;
}
Time (float T) //One Argument (float type) Constructor
{
Hr=(int) T:
Min=(int)((T-Hr)*100);
}
~Time() //Destructor
{
cout<<”Memory is released for the class Time”<<endl;
}
void display()
{
cout<<”Hr:”<<Hr<<”<<”:”<<”Min:”<<Min;
cout<<endl;
}
};
void main()
{
Time T; //Invoke the Default Constructor
T.display();
T=Time(4,12); //Invoke the 2 argument Constructor
Time T1(5.30); //Invoke the 1 argument Constructor
T1.display();
}
|
|
|
