C++ Assignment Operator
This page answers questions like these:
- How to write an assignment operator in C++?
- How to code an assignment operator in C++?
- How to program an assignment operator in C++?
- How to do an assignment operator in C++?
How to Write an Assignment Operator in C++?
// 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 Declaration:
- 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.
- Operator Definition:
- 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;”).
Difference Between char* and char  and char s[n]
Difference Between char* s = "string"; and char s = "string";
What is TCP Keep Alive?
How to Use TCP Keep Alive?
Static Member Function Declaration and Definition
Static Assertion / Compile-Time Assertion
Home > C++ > C++ Assignment Operator
Tags: assignment operator, C++