6.4. Why Overload Operators?

C++ doesn't force you to overload operators, so why bother? Let's consider the following.

int i, j, k;                  // integers 
float m, n, p;                // floats
k = i + j;                    // integer addition and assignment
p = m + n;                    // floating addition and assignment

Complex v, x, y;              // Complex numbers
String a, b, c;               // String objects
v = Complex_add(x, y);        // Complex addition and assignment
c = concat(a, b);             // String concatenation, assignment

The compiler overloads the + operator for built-in integer and float types by default, producing integer addition with i+j and floating addition with m+n. Here, Complex_add() and concat() perform Complex addition and String concatenation, but this approach forces users to remember function names and data ...

Get Navigating C++ and Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.