Interview Questions
Operator Overloading · Study material
C++ Operator Overloading – Interview Questions
1. What is operator overloading?
Defining how an operator works for user-defined types by writing a function named operator@.
2. Which operators cannot be overloaded?
:: . .* ?: sizeof typeid alignof, and the cast operators such as static_cast.
3. Which operators must be member functions?
= (assignment), [] (subscript), () (function call) and -> (member access).
4. Why is operator<< for output a non-member?
Its left operand is std::ostream, which you cannot add members to; as a member of your class the call would read obj << cout.
5. Why make operator+ a non-member?
So implicit conversions apply to both operands and the operator is symmetric (2 * v and v * 2).
6. How do you distinguish prefix and postfix ++?
Postfix takes a dummy int parameter: T operator++(int). Prefix has none: T& operator++().
7. Why is prefix ++ often faster for class types?
Postfix must copy the old value to return it; prefix returns a reference to the modified object.
8. What should operator= return?
A reference to *this, so assignments can be chained (a = b = c).
9. What is the spaceship operator?
C++20's operator<=> (three-way comparison). Defining or defaulting it gives <, <=, > and >=.
10. What does defaulting operator== do?
Compares all members in order; the compiler also derives != from it.
11. Can operator overloading change precedence or arity?
No. Both are fixed by the language grammar.
12. What is a functor?
An object of a class that overloads operator(); it can be called like a function and carry state.
13. What is a conversion operator?
operator T() converts an object to T; marking it explicit prevents accidental implicit conversions.
14. Why use explicit operator bool?
It still works in conditions but prevents nonsense like adding the object to an int.
15. Why is overloading && and || discouraged?
The overloaded versions evaluate both operands, losing short-circuit behaviour.
16. Can you overload operators for built-in types only, e.g. int + int?
No; at least one operand must be a class or enumeration type.
17. What are user-defined literals?
operator""_suffix functions that create values from literals, e.g. 12.5_km.
18. Why should operator+ return by value?
It produces a new value; returning a reference would refer to a local or wrongly modify an operand.
19. What does operator-> return?
A raw pointer, or an object that overloads -> itself; the compiler applies -> repeatedly until it reaches a pointer.
20. Is operator overloading compile-time or run-time polymorphism?
Compile-time: the right function is chosen by overload resolution, unless the operator is a virtual member function.