⚙️ C++ Intermediate

What is operator overloading in C++?

Why Interviewers Ask This

This question targets practical, hands-on experience with C++. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Operator overloading defines custom behavior for operators when applied to user-defined types — making them work naturally like built-in types. class Vector2D { public: double x, y; Vector2D(double x = 0, double y = 0) : x(x), y(y) {} // Addition: Vector2D operator+(const Vector2D& other) const { return Vector2D(x + other.x, y + other.y); } // Compound assignment: Vector2D& operator+=(const Vector2D& other) { x += other.x; y += other.y; return *this; } // Equality: bool operator==(const Vector2D& other) const { return x == other.x && y == other.y; } bool operator!=(const Vector2D& other) const { return !(*this == other); } // Unary negation: Vector2D operator-() const { return Vector2D(-x, -y); } // Subscript: double& operator[](int i) { return i == 0 ? x : y; } // Comparison (C++20 -- spaceship operator): auto operator<=>(const Vector2D&) const = default; // Friend: output stream: friend std::ostream& operator<<(std::ostream& os, const Vector2D& v) { return os << "(" << v.x << ", " << v.y << ")"; } }; // Usage: Vector2D a(1, 2), b(3, 4); Vector2D c = a + b; // (4, 6) a += b; std::cout << c << "\n"; // (4, 6). Rules: can't overload: ::, ., .*, ?:; can't change arity or precedence; at least one operand must be a user-defined type. Member vs free function: use member for operators that modify the object (+=, [], (), ->); use free (friend) for symmetric operators (+, -, ==, <<) to allow commutativity. Spaceship operator (<=>, C++20): define once, get all six comparison operators automatically.

Pro Tip

This topic has C++-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.