When we want to initialize an object with use of some other object then copy constructor may be used.
It require reference to the object who's values will be copied to create new object. However it can also work without reference variable.
#include<iostream.h>
#include<conio.h>
class abc
{
int a,b;
public:
abc()
{
a=0;
b=0;
}
abc(int x,int y)
{
a=x;
b=y;
}
abc(abc &k)//copy constructor
{
a=k.a;
b=k.b;
}
void show()
{
cout<<"a= "<<a<<endl<<"b= "<<b<<endl;
}
};
void main()
{
clrscr();
int l,m;
cout<<"Enter two no." <<endl;
cin>>l>>m;
abc ob1,ob2(l,m),ob3(ob2);
ob1.show();
ob2.show();
ob3.show();
getch();
}
In which case Copy Constructor is executed
1. When we pass object to a constructor then copy constructor provided by the programmer is executed.
2. When object is passed to a function
3. When object is assigned to another object using = operator
No comments:
Post a Comment