Constructor Overloading In C++
In C++, We can have more than one constructor in a class with
same name, as long as each has a different list of arguments.This concept is
known as Constructor Overloading.
Fig: Constructor Overloading In C++ |
Syntax:
Class classname
{
----
-----
}
Class
classname(argument)
{
----
------
};
Program:
#include<iostream.h>
#include<conio.h>
class
BCA
{
int
a,b,c;
public:
BCA()
{
a=b=c=0;
}
BCA(int
a)
{
this->a=this->b=this->c=a;
}
BCA(int
a, int b)
{
this->a=a;
this->b=b;
this->c=a+b;
}
void
display()
{
cout<<”a=”<<a;
cout<<”b=”<<b;
cout<<”c=”<<c;
}
};
void
main()
{
BCA
a1;
a1.display();
BCA
a2(10);
a2.display();
BCA
a3(20,30);
a3.display();
getch();
}
Output:
a=0
b=0 c=0 a=10 b=10 c=10 a=20 b=30 c=9915
Class classname
{
----
-----
}
Class
classname(argument)
{
----
------
};
Program:
#include<iostream.h>
#include<conio.h>
class
BCA
{
int
a,b,c;
public:
BCA()
{
a=b=c=0;
}
BCA(int
a)
{
this->a=this->b=this->c=a;
}
BCA(int
a, int b)
{
this->a=a;
this->b=b;
this->c=a+b;
}
void
display()
{
cout<<”a=”<<a;
cout<<”b=”<<b;
cout<<”c=”<<c;
}
};
void
main()
{
BCA
a1;
a1.display();
BCA
a2(10);
a2.display();
BCA
a3(20,30);
a3.display();
getch();
}
Output:
a=0
b=0 c=0 a=10 b=10 c=10 a=20 b=30 c=9915
No comments:
Post a Comment