In copy
constructor, we copy a constructor to another object. When we have to make a
constructor with same values of attributes which another constructor have, then
we use copy constructor technique.
I give an
example code in C++ to understand copy constructor concept.
#include<iostream>
using namespace std;
class distancee
{ private:
float inches;
public:
distancee(
):feet(0),inches(0.0)
{
}
distancee(int
ft,float in ):feet(ft),inches(in)
{ }
void
getdist()
{cin>>feet>>inches;}
void
showdist()
{cout<<feet<<inches;}
};
int main()
{ distancee dist1(11,6.25);
distancee dist2(dist1);
distancee dist3=dist1;
cout<<"\ndist1=";dist1.showdist();
cout<<"\ndist2=";dist2.showdist();
cout<<"\ndist3=";dist3.showdist();
system("pause");
return 0;
}
Here:
1. 1. distancee(int ft,float in
):feet(ft),inches(in){}
2. distancee dist1(11,6.25);
3. 3. distancee dist2(dist1);
In 1. We make a constructor of two attributes.
In 2. We pass values in constructor using object “dist1”.
In 3. We pass just “dist1”
object in constructor for copy constructor to “dist2”.
No comments:
Post a Comment