Copy constructor is a special kind of constructor which initializes an object using another object. Compiler always provides a default copy constructor but if needed it can be over-ridden by programmer to meet the requirements.
Assignment operator is basically assigning the new values to already created object. In this case object initialization doesn’t happen as it is already done.
For eg:
class Base{
};
Base b1;
Base b2 = b1; /* Copy constructor as initialization also needs to done */
Base b3;
b3 = b2; /* Assignment operator as object is already created */
Copy Constructor | Assignment Operator |
---|---|
It initializes an object using another object. | It assigns value of an object to another object. |
Since it initializes the object, hence new memory block is allocated and assigned to new object. | Memory is already allocated, hence no new memory block is allocated. |
This is a overloaded constructor. | This is a overloaded operator |
It can be replaced by default constructor plus assignment operator. | This can’t be replaced. |
If a new object needs to be created before copying the value then copy constructor is called. | If no new object needs to be created before copying the value then assignment operator is called. |
Let’s have a look into a sample program.
#include <iostream>
using namespace std;
class Base {
public:
Base () {
cout << "Default constructor !!" << endl;
}
Base (const Base& b) {
cout << "Copy constructor !!" << endl;
}
Base& operator= (const Base& b) {
cout << "Assignment operator !!" << endl;
}
};
int main() {
Base b1;
Base b2 (b1); /* Copy constructor as initialization also needs to done */
Base b3;
b3 = b2; /* Assignment operator as object is already created */
}
Let’s have a look into output of above program.
Default constructor !!
Copy constructor !!
Default constructor !!
Assignment operator !!