C++ Copy constructor
We briefly mentioned about the copy constructor in the previous pages
we used the copy constructor
A copy CONSTRUCTOR is used for declare and initialize an object from another object
below example
would define the object I2 and at the same time initialize it to the value of I1. Another form of
This statement is
The process of initializing through a copy constructor is known as copy initialization member let us take example in the below
will not invoke the copy constructor. However it I1 , I2 are objects. This statement is legally and simply assigns the values of I1 to I2, member by member. This is the task of the overloaded assignment operator=. discuss in the next pages
A copy constructor takes a reference of an object of the same class as itself as an argument.
let us consider a simple example of constructing and using a copy constructor
as show in the program
<iostream>
using namespace std;
class code
{
id;
:
Code()
{
}
Code()
{
id=x.id;
}
display()
{
cout << id;
}
};
main()
{
code A(100);
code B(A);
code C=A;
code D;
D=A;
std::cout << "\n id of A:";
A.display();
std::cout<<"\n id of B:";
B.display();
std::cout<<"\n id if C:";
C.display();
std::cout<<"\n id of D:";
D.display();
}
|
id of A: 100
id of B: 100
id of C: 100
id of D: 100
|
A reference variable has been used as an argument to the copy constructor. We cannot Pass the argument by value to a copy constructor
When no copy constructor is defined the compiler supplies its own copy constructor