The Assignment Operator is when you replace the data with an already existing(previously initialized) object with
some other object’s data. Lets see an example:
// Assignment Operator
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class Assign
{
public:
Assign(int data)
{
this->data = data;
}
~Assign(){};
Assign& operator=(const Assign& rhs)
{
data = rhs.data;
return *this;
}
int data;
};
int main()
{
Assign assign(2); //Assign(int data) called
Assign assign2(42);
assign = assign2; // Assignment Operator Called
cout << assign.data << endl; //Prints 42
}
You can see here I call the assignment operator when I already initialized the Assign object. Then later I assign foo2 to
foo . All the changes to appear when you call that equal sign operator is defined in your operator= function
Copy Constructor:
Copy constructor on the other hand , is the complete opposite of the Assignment Constructor. It is used
to initialize an already initialized object. This means it copies all the data from the object you are assigning it to , without actually initializing the object that is being copied onto. Now Let’s take a look at the same code as before but modify the assignment constructor to be a copy constructor :
#include<iostream>
#include<string>
using std::cout;
using std::endl;
class Copy
{
public:
Copy(int data)
{
this->data = data;
}
~Copy(){};
Copy(const Copy& rhs)
{
data = rhs.data;
}
int data;
};
int main()
{
Copy copy(2); //copy(int data) called
Copy copy2 = copy; // Copy Constructor called
cout << copy2.data << endl;
}
As you can see here Copy copy2 = copy; in the main function I immediately assign the object before actually initializing it, which as said before means it’s a copy constructor. And notice that I didn’t need to pass the parameter int for the
copy2 object since I automatically pulled the previous data from the object copy.