The Assignment Operator is when you replace the data with an already existing(previously initialized) object with some other object's data. Lets take this as an example:
// Assignment Operator
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class Foo
{
public:
Foo(int data)
{
this->data = data;
}
~Foo(){};
Foo& operator=(const Foo& rhs)
{
data = rhs.data;
return *this;
}
int data;
};
int main()
{
Foo foo(2); //Foo(int data) called
Foo foo2(42);
foo = foo2; // Assignment Operator Called
cout << foo.data << endl; //Prints 42
}
You can see here I call the assignment operator when I already initialized the foo
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. You can see a runnable output here: http://cpp.sh/3qtbm