Constructor
overloading
Function
overloading can be applied for constructors, as constructors are special
functions of classes. A class can have more than one constructor with different
signature. Constructor overloading provides flexibility of creating multiple
type of objects for a class.
Compiler
identifies a given member function is a constructor by its name and the return
type.
#include<iostream>
using namespace std;
class add
{
int num1, num2, sum;
public:
add()
{
cout<<"\n Constructor without parameters.. ";
num1= 0;
num2= 0;
sum = 0;
}
add ( int s1, int s2 )
{
cout<<"\n Parameterized constructor... ";
num1= s1;
num2=s2;
sum=0;
}
add (add &a)
{
cout<<"\n Copy Constructor ... ";
num1= a.num1;
num2=a.num2;
sum = 0;
}
void getdata()
{
cout<<"\nEnter data ... ";
cin>>num1>>num2;
}
void addition()
{
sum=num1+num2;
}
void putdata()
{
cout<<"\n The numbers are..";
cout<<num1<<'\t'<<num2;
cout<<"\n The sum of the numbers are.. "<<
sum;
}
};
int main()
{
add a, b (10, 20) , c(b);
a.getdata();
a.addition();
b.addition();
c.addition();
cout<<"\n Object a : ";
a.putdata();
cout<<"\n Object b : ";
b.putdata();
cout<<"\n Object c.. ";
c.putdata();
return 0;
}
Constructor without parameters..
Parameterized constructor...
Copy Constructor ...
Enter data ... 20 30
Object a :
The numbers are..20 30
The sum of the numbers are.. 50
Object b :
The numbers are..10 20
The sum of the numbers are.. 30
Object c..
The numbers are..10 20
The sum of the numbers are.. 30
//constructor
declared as outline member function
#include<iostream>
using namespace std;
class Perimeter
{
int l, b, p;
public:
Perimeter ();
Perimeter (int);
Perimeter (int,int);
Perimeter (Perimeter&);
void Calculate();
};
Perimeter :: Perimeter ()
{
cout<<"\n Enter the value of length and breath";
cin>>l>>b;
cout<<"\n\nNonParameterizd constructor ";
}
Perimeter ::Perimeter (int a)
{
l=b=a;
cout<<"\n\n Parameterizd constructor with one
argument ";
}
Perimeter ::Perimeter (int l1, int b1)
{
cout<<"\n\n Parameterizd constructor with 2 argument
";
l=l1;
b=b1;
}
Perimeter ::Perimeter (Perimeter &p)
{
l= p.l;
b= p.b;
cout<<"\n\n copy constructor ";
}
void Perimeter ::Calculate(){
p = 2*(l+b);
cout<<p;
}
int main ()
{
Perimeter Obj;
cout<<"\n perimeter of rectangle is ";
Obj. Calculate ();
Perimeter Obj1(2);
cout<<"\n perimeter of rectangle ";
Obj1.Calculate ();
Perimeter Obj2 (2, 3);
cout<<"\n perimeter of rectangle ";
Obj2.Calculate ();
Perimeter obj3 (Obj2);
cout<<"\n perimeter of rectangle ";
obj3.Calculate ();
return 0;
}
Enter the value of length and breath 10 20
Non Parameterizd constructor
perimeter of rectangle is 60
Parameterizd constructor with one argument
perimeter of rectangle 8
Parameterizd constructor with 2 argument
perimeter of rectangle 10
copy constructor
perimeter of rectangle 10
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.