Assignment operator
suggest changeThe assignment operator replaces the data of an already existing (previously initialized) object with some other object’s data. Let’s 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 that the assignment operator is called when foo is already initialized. Then foo2 is assigned to foo. What that operator does is defined in operator=. You can see a runnable output here: http://cpp.sh/3qtbm
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents