How to Overload Assignment Operator in C++: Syntax and Example
To overload the
operator= in C++, define it as a member function that takes a const reference to the same class and returns a reference to *this. This allows you to customize how objects are assigned to each other.Syntax
The assignment operator overload is a member function with this general form:
ClassName& operator=(const ClassName& other);- It takes a constant reference to another object of the same class.
- It returns a reference to the current object (
*this) to allow chaining assignments.
cpp
ClassName& operator=(const ClassName& other) { if (this != &other) { // copy data from other to this object } return *this; }
Example
This example shows a simple class Number that overloads the assignment operator to copy the value from one object to another safely.
cpp
#include <iostream> class Number { private: int value; public: Number(int v = 0) : value(v) {} // Overload assignment operator Number& operator=(const Number& other) { if (this != &other) { // avoid self-assignment value = other.value; } return *this; } void print() const { std::cout << "Value: " << value << std::endl; } }; int main() { Number a(5); Number b; b = a; // uses overloaded assignment operator b.print(); return 0; }
Output
Value: 5
Common Pitfalls
Common mistakes when overloading the assignment operator include:
- Not checking for self-assignment, which can cause errors if the object assigns to itself.
- Not returning
*this, which breaks chaining likea = b = c;. - For classes managing dynamic memory, forgetting to properly free old resources before copying new ones causes memory leaks.
cpp
/* Wrong way: missing self-assignment check and return */ Number& operator=(const Number& other) { value = other.value; // no self-check return *this; // added missing return } /* Right way: */ Number& operator=(const Number& other) { if (this != &other) { value = other.value; } return *this; }
Quick Reference
- Use
ClassName& operator=(const ClassName& other)signature. - Check
if (this != &other)to avoid self-assignment. - Return
*thisto allow chaining. - Handle dynamic memory carefully if your class owns resources.
Key Takeaways
Always define assignment operator as a member function returning a reference to *this.
Check for self-assignment to prevent errors.
Return *this to support chained assignments.
Manage dynamic resources carefully to avoid leaks.
Overloading assignment operator customizes how objects copy data.