C++ lets you define how operators work for user types—enabling natural syntax like v + w or streaming to std::cout.
Example: streaming
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << "(" << v.x << ", " << v.y << ")";
}
Overload operators to match intuitive expectations—surprising semantics confuse maintainers.
Important interview questions and answers
- Q: Which operators cannot be overloaded?
A:::,.,.*,?:,sizeof, and others—see standard for full list. - Q: member vs free function operators?
A: Symmetric operators like+are often free functions; compound assignments can be members.
Self-check
- Why overload operator<< for ostream?
- What makes an operator overload surprising?
Pitfall: Overloaded operators should behave intuitively—do not make + subtract unless you enjoy code review pain.
Interview prep
- Why overload operator<<?
Enables streaming custom types to
std::coutand other ostreams naturally.- Surprising overloads?
Operators should match intuitive semantics—surprising behavior confuses maintainers and reviewers.