Classes and objects · core
Function and operator overloading
Overloading gives one name several versions with different parameters; the compiler picks one from the argument types. Operator overloading lets your own types use +, == or <<.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Overloading: the same name with different parameter types or counts, in the same scope. The compiler picks the version at compile time from the argument types (compile-time polymorphism).
- The return type alone cannot overload a function:
int f()anddouble f()cannot both exist. - If no single version is the best match, the call is ambiguous and does not compile. With f(long) and f(float), the call f(0) is ambiguous.
- Operator overloading:
Point operator+(const Point& a, const Point& b). At least one operand must be a class or enum type, so you cannot change how + works for two ints. - You cannot overload ::, ., .* or ?:, create new operators, or change an operator's precedence or number of operands.
- operator<< for output must be a non-member,
ostream& operator<<(ostream& os, const Point& p), and it returns os so calls can chain. It is often a friend, to reach private members. - Define operator< as a strict ordering (a < a is false) so that std::sort, std::set and std::map can order your type.
- Overloading is not overriding: overloading is chosen at compile time from the argument types; overriding (a virtual function) is chosen at runtime from the real object.
The red pen
Common traps: mistake → fix
Mistake: Two functions can differ only by return type
Fix: the parameters must differ.
Mistake: Any operator can be overloaded
Fix: ::, ., .* and ?: cannot.
Mistake: operator<< can be a member of Point
Fix: the left operand is the ostream, so it must be a non-member.
Mistake: Overloading and overriding are the same thing
Fix: one is decided at compile time, the other at runtime.
Easy to hard
Questions interviewers ask, easy to hard
- What is the difference between overloading and overriding?
- Can two functions differ only in their return type?
- Overload + and << for a Point class.
- Which operators cannot be overloaded?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.