Just like function overloading, constructors can be overloading. Since
C++ permits function overloading and constructors are special functions in a
class, they also overloaded. This implies that within a class we can have more
than one constructor. These overloaded constructors are distinguished either by
the number of arguments or by the data types of the arguments.
example: number(); //no arguments
number(int); //one arguments
number(int, int); //two arguments
number(int, float); //differed by the datatype of arguments
program:
#include<iostream>
usage namespace std;
class student
{
char *name;
char rollno;
public:
student() // constructor
with no arguments
{
cout<<"Enter
the Name and Rollno:";
cin>>name;
cin>>rollno;
}
student(char *s, char r)
{
strcpy(name
s); //overloaded constructor
rollno=r;
}
student(student
&p) //overloaded Constructor
{
strcpy(name,p.name);
rollno=p.rollno;
}
void didplay();
};
void student::display()
{
cout<<"Name="<<name;
cout<<"Rollno="<<rollno;
}
void main()
{
student s;
s.display();
student s1("ABC","A101");
s1.display();
student
s2("xyz","A102");
s2.display();
}
Result :
Enter the Name and Rollno: pqr A103
Name = pqr
Rollno =A103
Name = ABC
Rollno =A101
Name = xyz
Rollno =A102
0 comments:
Post a Comment