Constructor Overloading
- Like methods, constructor can also be overloaded.
- A constructor is said to be overloaded when the same constructor with different
number and types of arguments initializes an object.
to understand.
Syntax :
class class-name
{
private :
data member;
public :
class-name() //default constructor
{
// statements
}
class-name(list of parameters) // overloading of constructor
{
//statements
}
};
Example :
#include <iostream.h>
#include <conio.h>
class Student
{
private:
int rollno;
int fee;
float marks;
public :
Student() //default constructor
{
cout<<"Default constructor called";
}
Student(int r, int f)//overloaded constructor
{
rollno=r;
fee=f;
}
Student(int r,int f,int m)//overloaded constructor
{
rollno=r;
fee=f;
marks=m;
}
void display()
{
cout<< "Roll no : " <
}
void display1()
{
cout<< "Roll no : " <
cout<< "\nMarks : "<
Student std1(2,5000);
std1.display();
cout<< "\n\nCalling overloaded constructor2: \n\n" ;
Student std2(2,5000,85.3);
std2.display1();
getch();
}
Output :
Description :
We have three overloaded constructors:
-Student()
-Student(int r,int f)
-Student(int r,int f,float m)
The first one is the default constructor while the other two are parameterized constructor.
These are overloaded because we have different number of parameters and different data type of parameters.
As in default constructor there are not any parameter while in second one two parameters
are there both of int type while in the third 3 parameters are there, two of int and one of
float data type.
Hence the number and type of parameters are different , so these are overloaded constructors.
0 comments:
Post a Comment