// Handles OBJECT1 = OBJECT2; where both objects are of type CLASS_NAME.
CLASS_NAME& operator = (const CLASS_NAME& op2);
// Handles OBJECT = string; (string is a standard C++ class)
CLASS_NAME& operator = (const string& op2);
// Handles OBJECT = char*;
CLASS_NAME& operator = (const char* op2);
Operator functions are generally declared to be public, but can be private or protected if you want. If an assignment operator is private, assignment is not allowed outside the class.
The lvalue (i.e. object or expression on the left-hand side that’s being written to) is accessed via *this.
The rvalue (i.e. object or expression on the right-hand side that’s being read from) is accessed via op2 (or whatever variable name you choose).
In the case of “OBJECT1 = OBJECT2;”, the first line of the assignment operator body should normally be: “if (this != &op2)”. This is because you don’t want to copy something to itself when both sides of the assignment are the same. Normally this situation wouldn’t occur, but if it ever did, you’d want to prevent it causing a crash or some other bizarre behaviour.
The last line of an assignment operator body is normally: “return *this;”. This allows the lvalue to be used again in another assignment (e.g. “a = b = c;”) or an operation requiring an lvalue (e.g. “(Object1 = Object2) = Blah;”).