Overloaded Operations and Conversions#

Based on C++ Primer, 5th ed., Chapter 14: Overloaded Operations and Conversions, this post summarizes design principles for operator overloading, implementation idioms for major operators, Functors operator(), std::function, and conversion operators operator TYPE().

1. Operator Overloading Fundamentals & Member vs. Nonmember Guidelines#

Overloaded operators are functions named with the operator keyword followed by the operator symbol (operator+, operator=, operator(), etc.).

  • Four Operators That Cannot Be Overloaded: Scope resolution ::, member selection ., pointer-to-member dereference .* — whereas * and ->* can be overloaded, and the ternary conditional ?: operator cannot be overloaded.
  • Operators You Should Not Overload: Overloading logical AND (&&), logical OR (||), or the comma operator (,) loses built-in short-circuit evaluation and order-of-evaluation guarantees, so they should not be overloaded. The unary address-of operator (&) should also not be overloaded for class types.

Choosing Member (this) vs. Nonmember (friend) Implementation#

CategoryTarget OperatorsRationale & Core Rules
Must Be Member= (assignment), [] (subscript), () (call), -> (member access arrow)Required by the C++ language standard to be declared exclusively as member functions (declaring them as nonmembers is a compile error).
Should Be Member+=, -=, *= (compound assignment)
++, -- (increment/decrement), * (dereference)
Directly mutate the object’s state or are unary operations tightly bound to the class type.
Should Be Nonmember
friend if needed
+, -, *, / (arithmetic)
==, !=, <, > (equality/relational)
<<, >> (I/O streams)
Symmetry & Left-Hand Implicit Conversion: A member operator requires the left-hand operand to be *this. If operator+ were a member of std::string, STRING_INSTANCE + "hi" would work, but "hi" + STRING_INSTANCE would fail to compile because the left operand is const char*! Defining symmetric operators as nonmembers allows implicit conversions on both left and right operands equally.

2. Implementation Idioms by Operator#

OperatorSignature PatternKey Implementation Rules
Output (<<)ostream& operator<<(ostream &os, const CLASS &x);Must be a nonmember function — defining it as a member of CLASS cannot match the cout << CLASS_INSTANCE syntax. Minimize formatting and return os.
Input (>>)istream& operator>>(istream &is, CLASS &x);Nonmember function. Input can fail at runtime, so always check if (is) after reading, and if it fails, reset x = CLASS(); to leave the object in a valid default state.
Arithmetic (+) vs. Compound (+=)CLASS& CLASS::operator+=(const CLASS &rhs);
CLASS operator+(const CLASS &lhs, const CLASS &rhs);
Implement operator+= as a member function first, then implement nonmember operator+ by copying lhs, delegating to += rhs, and returning by value CLASS.
Subscript ([])ELEM& operator[](size_t n);
const ELEM& operator[](size_t n) const;
Always define both non-const and const versions. This allows modifying elements on non-const objects while still reading elements on const objects.
Prefix vs. Postfix (++, --)Prefix: CLASS& operator++();
Postfix: CLASS operator++(int);
Postfix takes an unused dummy int parameter solely to distinguish its signature from prefix. Prefix returns an lvalue reference CLASS& to the incremented *this; postfix saves a copy of the old state, calls ++*this, and returns the old copy by value CLASS.
Member Access (*, ->)T& operator*() const;
T* operator->() const;
Used in smart pointers and iterators. For an object CLASS_INSTANCE, CLASS_INSTANCE->MEMBER is evaluated as (CLASS_INSTANCE.operator->())->MEMBER, so operator->() must return a raw pointer or another object that defines operator->.
// Prefix vs. Postfix Increment Implementation
class Ptr {
public:
  Ptr& operator++() {        // Prefix (++p): increment and return reference to *this
    ++curr;
    return *this;
  }
  Ptr operator++(int) {      // Postfix (p++): dummy int parameter! Save old state, call prefix, return old copy
    Ptr ret = *this;
    ++*this;                 // Reuse prefix operator++
    return ret;
  }
private:
  int *curr;
};

3. Function-Call Operator operator() and Functors#

When a class overloads the function-call operator operator(), instances of that class can be invoked like functions. Such classes are called Function Objects or Functors.

  • Unlike ordinary functions, a functor is a class and can store internal state in member variables across calls.
  • When the compiler encounters a lambda expression, it translates the lambda into an unnamed functor class — a closure class — with an overloaded operator() const and creates a temporary instance of it; see Lambda Expressions.
struct AbsInt {
  int operator()(int val) const {
    return val < 0 ? -val : val;
  }
};

AbsInt absObj;           // Create an instance of the functor class
int ui = absObj(-42);    // Calls absObj.operator()(-42) -> returns 42

Passing a Functor: <> Template Type Argument vs. () Function Call Argument#

The core principle when passing a comparator functor is that <> template arguments expect a type, whereas () function arguments expect an instance:

Aspect<> Template Type Argument() Function Call Argument
Target PassedFunctor class type itself — std::greater<T>, no ()Functor instance — std::greater<T>(), requires () to construct a temporary
Typical UsageContainer declarations — priority_queue, set, mapAlgorithm function calls — sort, find_if, etc.
Passing a Lambda Directly❌ A lambda expression is an instance of an anonymous class, not a type, so it cannot go directly inside <> — bind it to a variable, pass decltype to <>, and pass the variable to the constructor ()✅ Expects an instance, so an inline lambda expression can be passed directly inside ()
// 1. Container <> template type argument (std::priority_queue)
// (a) Functor class: pass the type itself inside <> without ()
std::priority_queue<int, std::vector<int>, std::greater<int>> pq1;

// (b) Lambda: bind to a variable, pass decltype to <>, and pass the variable to the constructor
auto cmp = [](int a, int b) { return a > b; };
std::priority_queue<int, std::vector<int>, decltype(cmp)> pq2(cmp);

// 2. Algorithm () function call argument (std::sort)
//    Parameter expects an object, so pass a temporary functor () or inline lambda directly
std::vector<int> v = {3, 1, 2};
std::sort(v.begin(), v.end(), std::greater<int>());
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

4. Callable Objects and std::function#

C++ has four kinds of callable objects that can be invoked like functions:

  1. Ordinary functions
  2. Function pointers
  3. Lambda expressions — instances of anonymous functor classes
  4. Objects of functor classes that define operator()

Although these four have completely distinct C++ types, they can share the same call signature — return type and parameter types, such as int(int, int). To store heterogeneous callables with the same call signature in a single container such as an operator dispatch map, use std::function<RETURN_TYPE(ARGS...)> from <functional>:

#include <functional>
#include <map>
#include <string>

int add(int i, int j) { return i + j; }                  // 1. Ordinary function
auto mod = [](int i, int j) { return i % j; };           // 2. Lambda (anonymous functor instance)
struct Div { int operator()(int i, int j) { return i / j; } }; // 3. Functor class

// Different underlying types, but all share the call signature int(int, int)!
std::map<std::string, std::function<int(int, int)>> binops = {
  {"+", add},                  // Function pointer
  {"-", std::minus<int>()},    // Standard library functor instance
  {"/", Div()},                // User-defined functor instance
  {"*", [](int i, int j) { return i * j; }}, // Inline lambda instance
  {"%", mod}                   // Named lambda instance
};

int r1 = binops["+"](10, 5);   // 15
int r2 = binops["*"](10, 5);   // 50

5. Conversion Operators operator TYPE() const and explicit#

  • Converting Constructor CLASS(OTHER_TYPE): Converts another type OTHER_TYPE into a CLASS object — see Classes: explicit.
  • Conversion Operator operator TYPE() const: Special member functions such as operator int() const and operator bool() const that convert a CLASS object into another type.
    • Must be a member function; because the operator name itself names the return type, specify no separate return type, leave the parameter list empty, and generally mark it const.

Dangers of Implicit Conversion and explicit Conversion Operators (C++11)#

Non-explicit conversion operators often trigger surprising silent conversions in arithmetic expressions. C++11 introduced explicit conversion operators to require an explicit cast (static_cast<TYPE>(obj)).

  • The Contextual bool Exception — explicit operator bool() const:
    • Even when a conversion operator to bool is marked explicit, the compiler automatically applies it in condition contexts — if, while, and for conditions, logical operators !, &&, ||, and the ternary ?: condition!
    • Canonical Example — std::istream (std::cin):
      • The standard library’s std::istream defines explicit operator bool() const. If std::istream instead had a non-explicit operator bool(), a reversed-arrow typo like std::cin << 42; would implicitly convert cin to bool (0 or 1) and silently compile as the integer bit-shift 1 << 42.
      • Marking it explicit operator bool() const rejects std::cin << 42; at compile time while still allowing while (std::cin >> VAR) to convert the returned std::istream& to bool automatically in the loop condition — see IO Library: Evaluating Stream State.
class SmallInt {
public:
  SmallInt(int i = 0) : val(i) {}

  // explicit conversion operator: blocks silent int conversion, allows static_cast
  explicit operator int() const { return val; }

  // explicit bool conversion: blocks arithmetic conversion, but auto-applies in if/while conditions!
  explicit operator bool() const { return val != 0; }

private:
  int val;
};

SmallInt si = 3;
// si + 3;                      // Compile error! explicit operator int() blocks silent conversion
int x = static_cast<int>(si) + 3; // OK: explicit cast is allowed
if (si) { /* ... */ }           // OK! Condition context automatically invokes explicit operator bool()