A copy constructor is used to declare and initialized an object from another object. But constructor enables an object to initialize itself when it is created. It is known as automatic initialization of object. So copy constructor is different from constructor.
For Example:
#include<iostream.h>
class copy
{
int id;
public:
copy()
{ }
copy(int a);
{
id=a;
}
copy(copy & x)
{
id=x.id;
}
void display(void)
{
cout<<id;
}
};
void main()
{
copy a(300);
copy b(a);
copy c=a;
copy d(b);
cout<<"\n ID of a: ";a.display();
cout<<"\n ID of b: ";b.display();
cout<<"\n ID of c: ";c.display();
cout<<"\n ID of d: ";d;display();
return();
}
Output of this program is:
ID of a: 300
ID of b: 300
ID of c: 300
ID of d: 300
For Example:
#include<iostream.h>
class copy
{
int id;
public:
copy()
{ }
copy(int a);
{
id=a;
}
copy(copy & x)
{
id=x.id;
}
void display(void)
{
cout<<id;
}
};
void main()
{
copy a(300);
copy b(a);
copy c=a;
copy d(b);
cout<<"\n ID of a: ";a.display();
cout<<"\n ID of b: ";b.display();
cout<<"\n ID of c: ";c.display();
cout<<"\n ID of d: ";d;display();
return();
}
Output of this program is:
ID of a: 300
ID of b: 300
ID of c: 300
ID of d: 300
Comments
Post a Comment