PadhaikoAll subjects

Operator Overloading

Object Oriented Programming (ENCT 151)

Open in the Padhaiko app

4.1 Overloadable and non-overloadable operators

Operator overloading lets C++ operators (+, -, ++, ==, <<, etc.) work on user-defined class types in a natural, readable way (c3 = c1 + c2; instead of c3 = c1.add(c2);). It is a form of compile-time polymorphism.

Overloadable vs. Non-Overloadable Operators in C++
CategoryOperators
Overloadable OperatorsArithmetic (+, -, *, /, %), Increment/Decrement (++, --), Relational (==, !=, <, >, <=, >=), Logical (&&, logical OR, !), Bitwise (&, bitwise OR, ^, ~, <<, >>), Assignment (=, +=, -=, etc.), Subscript [], Call (), Member access ->, ->*, Memory (new, delete, new[], delete[]), Comma ,
Non-Overloadable OperatorsScope resolution ::, Member selection ., Pointer-to-member selection .*, Ternary conditional ?:, Size query sizeof (also typeid, alignof)

Fundamental Rules of Operator Overloading

  1. No New Operator Symbols: Only existing C++ operators can be overloaded (you cannot invent ** for exponentiation).
  2. Arity, Precedence, and Associativity Are Fixed: Unary operators remain unary, binary remain binary, and + always keeps lower precedence than *.
  3. At Least One User-Defined Operand: You cannot redefine how + works on two built-in ints.
  4. Member-Only Operators: Assignment =, function call (), subscript [], and member access -> must be overloaded as non-static member functions, never as friend functions.

4.2 Syntax of operator overloading

An overloaded operator is a special function whose name starts with the operator keyword followed by the operator symbol:

General Operator Function PrototypeC++
// Inside a class (member function):
ReturnType operator@(ParameterList);

// Outside a class (non-member / friend function):
ReturnType operator@(ClassName lhs, ...);

4.3 Operator overloading using member operator functions

When an operator is overloaded as a member function, the left-hand operand (for binary) or the single operand (for unary) is passed implicitly via the this pointer:

Binary + as a Member FunctionC++
class Complex {
    double re, im;
public:
    Complex(double r = 0, double i = 0) : re(r), im(i) {}
    Complex operator+(const Complex &rhs) const {
        return Complex(re + rhs.re, im + rhs.im);
    }
};

Limitation of member operators: c1 + 5.0 can work if a converting constructor Complex(double) exists, because c1.operator+(Complex(5.0)) converts the right operand; however, 5.0 + c1 fails for a member operator because 5.0 is a primitive double and cannot invoke 5.0.operator+(c1).


4.4 Operator overloading using non member functions

To support expressions where the left-hand operand is a built-in type (such as 5.0 + c1 or cout << c1), overload the operator as a non-member function (usually declared friend inside the class so it can read private members):

AspectMember Operator FunctionNon-Member (friend) Operator Function
Unary Arguments0 explicit arguments (this is operand)1 explicit argument
Binary Arguments1 explicit argument (this is left operand)2 explicit arguments (lhs, rhs)
Left Operand ConversionImplicit conversions do not apply to thisImplicit conversions apply to both operands
Mandatory Cases=, (), [], -><<, >> with ostream/istream, scalar + obj

4.5 Unary operator overloading

Unary operators operate on a single object (e.g., -obj, ++obj, obj++, !obj).

Prefix vs. Postfix ++ and --

Because both prefix (++c) and postfix (c++) use the same ++ symbol, C++ uses a dummy int parameter to distinguish postfix:

Prefix and Postfix Increment OverloadingC++
#include <iostream>
using namespace std;

class Counter {
    int val;
public:
    Counter(int v = 0) : val(v) {}
    Counter &operator++() {       // Prefix: ++c
        ++val;
        return *this;
    }
    Counter operator++(int) {     // Postfix: c++
        Counter old = *this;
        ++val;
        return old;
    }
    int get() const { return val; }
};

int main() {
    Counter c(5);
    cout << (++c).get() << " ";   // Increments to 6, prints 6
    cout << (c++).get() << " ";   // Returns copy (6), then increments to 7
    cout << c.get() << endl;      // Prints 7
    return 0;
}

4.6 Binary operator overloading

Binary operators take two operands: arithmetic (+, -, *), relational (==, <), or compound assignment (+=).


4.7 Type conversion between objects

While C++ converts built-in types automatically (int to double), conversions involving class types require programmer-defined rules across three scenarios:

Three Categories of Class Type Conversion
Conversion DirectionMechanismWhere Defined
Basic Type -> Class TypeSingle-argument converting constructor ClassName(BasicType x)Inside the destination class
Class Type -> Basic TypeConversion operator function operator BasicType() constInside the source class (no return type written, no args)
Class A -> Class BEither converting constructor B(const A &) in B, OR conversion operator operator B() const in AChoose one (defining both causes ambiguity)

4.8 Explicit constructors

A single-argument constructor (or a constructor where all subsequent arguments have defaults) acts implicitly as a converting constructor. Sometimes implicit conversion causes silent bugs—for example, passing an integer 10 where a Vector of size 10 is expected, or comparing vec == 10.

Prefixing a constructor with explicit disables implicit conversions and copy-initialization (T obj = val;), permitting only direct initialization (T obj(val); or static_cast<T>(val)):

Preventing Unwanted Implicit Conversions with explicitC++
class Buffer {
    int size;
public:
    explicit Buffer(int s) : size(s) {}
    int getSize() const { return size; }
};

void printSize(Buffer b) { /* ... */ }

int main() {
    Buffer b1(64);        // OK: direct initialization
    // Buffer b2 = 64;    // Compile error: copy-initialization blocked by explicit
    // printSize(64);     // Compile error: implicit int -> Buffer blocked
    printSize(Buffer(64)); // OK: explicit conversion
    return 0;
}

Worked Examples

Example 1

1 (8 marks)

Write a C++ class Distance storing feet (int) and inches (double, normalized so 0 <= inches < 12). Overload:

  1. Binary + (member) to add two Distance objects,
  2. Prefix ++ to add 1 inch (normalizing overflow),
  3. operator double() const to convert Distance to total feet (double), and
  4. Relational < as a friend function.

Trace the result for d1(5, 8.0) and d2(3, 7.0).

Normalization Helper and Operator Definitions: Whenever inches reach or exceed 12.0, carry int(inches / 12) into feet and keep the remainder in inches:

Distance Class with Multiple Overloaded Operators and ConversionC++
#include <iostream>
using namespace std;

class Distance {
    int feet;
    double inches;
    void normalize() {
        while (inches >= 12.0) {
            inches -= 12.0;
            ++feet;
        }
    }
public:
    Distance(int f = 0, double in = 0.0) : feet(f), inches(in) { normalize(); }

    Distance operator+(const Distance &rhs) const {
        return Distance(feet + rhs.feet, inches + rhs.inches);
    }

    Distance &operator++() {
        inches += 1.0;
        normalize();
        return *this;
    }

    operator double() const {
        return feet + inches / 12.0;
    }

    friend bool operator<(const Distance &a, const Distance &b) {
        return (a.feet * 12.0 + a.inches) < (b.feet * 12.0 + b.inches);
    }

    void show() const { cout << feet << "ft " << inches << "in"; }
};

int main() {
    Distance d1(5, 8.0), d2(3, 7.0);
    Distance d3 = d1 + d2;
    ++d3;
    double totalFeet = d3; // Uses operator double() const
    cout << "d3 = "; d3.show();
    cout << ", in feet = " << totalFeet << ", d2 < d1? " << (d2 < d1) << endl;
    return 0;
}

Tracing for d1(5, 8.0) and d2(3, 7.0):

  • d1 + d2: feet = 5 + 3 = 8, inches = 8.0 + 7.0 = 15.0 -> normalized to 9 ft 3 in.
  • ++d3: adds 1.0 inch -> 9 ft 4 in.
  • double totalFeet = d3: invokes operator double() const -> 9 + 4.0 / 12.0 = 9.33333 (printed as 9.33333).
  • d2 < d1: 3*12 + 7 = 43 < 5*12 + 8 = 68 -> 1 (true).
Answer:

Output: d3 = 9ft 4in, in feet = 9.33333, d2 < d1? 1

Example 2

2 (6 marks)

Demonstrate class-to-class type conversion between Polar (radius, angleRad) and Cartesian (x, y) using a converting constructor in Cartesian, and compute (x, y) for Polar(10.0, 0.0) and Polar(5.0, 3.14159265 / 2.0).

Choosing One Conversion Mechanism (Destination Converting Constructor): Cartesian(const Polar &p) reads p.getR() and p.getTheta() via public getters (or friend access) and sets x = r * cos(theta), y = r * sin(theta). We do not also define Polar::operator Cartesian(), avoiding ambiguity.

Polar to Cartesian Conversion via Converting ConstructorC++
#include <iostream>
#include <cmath>
using namespace std;

class Polar {
    double r, theta;
public:
    Polar(double rad, double ang) : r(rad), theta(ang) {}
    double getR() const { return r; }
    double getTheta() const { return theta; }
};

class Cartesian {
    double x, y;
public:
    Cartesian(double xx = 0, double yy = 0) : x(xx), y(yy) {}
    Cartesian(const Polar &p) { // Polar -> Cartesian
        x = p.getR() * cos(p.getTheta());
        y = p.getR() * sin(p.getTheta());
    }
    void show() const { cout << "(" << x << ", " << y << ")" << endl; }
};

int main() {
    Polar p1(10.0, 0.0);
    Polar p2(5.0, 3.141592653589793 / 2.0);
    Cartesian c1 = p1;
    Cartesian c2 = p2;
    c1.show();
    c2.show();
    return 0;
}

Tracing Coordinates:

  • For p1(10.0, 0.0): x = 10 * cos(0) = 10, y = 10 * sin(0) = 0.
  • For p2(5.0, pi/2): x = 5 * cos(pi/2) ~ 0 (IEEE floating point ~3.06e-16), y = 5 * sin(pi/2) = 5.
Answer:

c1 converts to (10, 0) and c2 converts to (0, 5) (with floating-point x near 3.06e-16 for pi/2).


Exercises

Exercises — Operator Overloading

Question 1

List the operators that cannot be overloaded in C++, and explain why operators like << (stream insertion) and expressions like 5 + obj must be overloaded as non-member (friend) functions.

Non-Overloadable Operators: The five classic non-overloadable operators in C++ are:

  1. :: (scope resolution)
  2. . (direct member access)
  3. .* (pointer-to-member access)
  4. ?: (ternary conditional)
  5. sizeof (along with typeid and alignof)

Why << and 5 + obj Require Non-Member Overloading: In a member operator lhs.operator op(rhs), the left operand lhs must be an object of the class you are writing (and no implicit conversion happens on lhs).

  • For cout << obj, the left operand is std::ostream (cout), whose class definition we cannot modify. Thus operator<<(ostream &, const MyClass &) must be a non-member (friend) function.
  • For 5 + obj, the left operand is int (5), which has no operator+(MyClass) method. A non-member friend MyClass operator+(int, const MyClass &) accepts int as its first parameter cleanly.
Answer:

Non-overloadable operators are ::, ., .*, ?:, and sizeof (typeid, alignof). << and 5 + obj require non-member (friend) overloads because their left-hand operands (ostream and int) are not objects of our user-defined class.

Question 2

How does C++ distinguish between prefix (++x) and postfix (x++) unary operator overloading? Write both functions for a Time class (seconds) and state what (++t) vs (t++) evaluates to when t starts at 10.

Prefix vs. Postfix Signature Convention:

  • Prefix (T &operator++()): Takes no parameter, increments the object first, and returns *this by reference (yielding the new value).
  • Postfix (T operator++(int)): Takes an unused dummy int parameter, saves a temporary copy of the original state, increments *this, and returns the saved copy by value (yielding the old value).

Trace for t = 10:

  • ++t increments t from 10 to 11 and evaluates to 11.
  • t++ returns a copy holding 11 while incrementing t to 12.
Answer:

Prefix uses T &operator++() (returns incremented *this, evaluating to 11), while postfix uses a dummy int parameter T operator++(int) (returns old copy 11 and leaves t at 12).

Question 3

Explain the three types of type conversions involving classes in C++, and state how ambiguity can occur in class-to-class conversion.

Three Conversion Categories:

  1. Basic Type -> Class Type: Implemented via a single-argument constructor ClassName(BasicType val) in the target class.
  2. Class Type -> Basic Type: Implemented via a member conversion operator operator BasicType() const in the source class (no return type, no parameters).
  3. Class A -> Class B: Implemented either as a converting constructor B(const A &) in destination class B, or as a conversion operator operator B() const in source class A.

Class-to-Class Ambiguity: If both A::operator B() const and B::B(const A &) are defined simultaneously, writing B b = a; gives the compiler two equally valid conversion paths (a.operator B() vs B(a)), causing an ambiguous conversion compile error. Define only one of the two.

Answer:

Basic-to-class uses a single-argument constructor; class-to-basic uses operator BasicType() const; class-to-class uses either a destination constructor or a source conversion operator. Defining both in class-to-class conversion creates an ambiguous-conversion compile error.

Question 4

What is the purpose of an explicit constructor? Show a code snippet where omitting explicit causes an unexpected implicit conversion and adding explicit catches it at compile time.

Purpose of explicit: Without explicit, any constructor callable with one argument acts as an implicit converter, allowing ClassType obj = arg; or passing arg silently to a function expecting ClassType. Marking the constructor explicit forces callers to construct objects intentionally (ClassType obj(arg); or ClassType(arg)).

Code Demonstration:

Effect of explicit ConstructorC++
class Meter {
    double m;
public:
    explicit Meter(double val) : m(val) {}
    double value() const { return m; }
};

void show(Meter x) { /* ... */ }

int main() {
    Meter m1(5.0);      // Valid: direct initialization
    // Meter m2 = 5.0;  // Error when explicit: implicit double -> Meter disabled
    // show(5.0);       // Error when explicit: must write show(Meter(5.0))
    return 0;
}
Answer:

explicit prevents single-argument constructors from performing silent implicit conversions (Meter m2 = 5.0; or show(5.0)), requiring direct initialization (Meter m1(5.0);).

Question 5

Overload operator+ and operator* for a Complex class (real, imag), and compute (2 + 3i) * (4 - i) + (1 + 2i). Show both the algebraic steps and the C++ output.

Complex Multiplication and Addition Rules: For a + bi and c + di:

  • (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
  • (a + bi) + (c + di) = (a + c) + (b + d)i
Complex Arithmetic with Overloaded + and *C++
#include <iostream>
using namespace std;

class Complex {
    double re, im;
public:
    Complex(double r = 0, double i = 0) : re(r), im(i) {}
    Complex operator+(const Complex &rhs) const {
        return Complex(re + rhs.re, im + rhs.im);
    }
    Complex operator*(const Complex &rhs) const {
        return Complex(re * rhs.re - im * rhs.im,
                       re * rhs.im + im * rhs.re);
    }
    void show() const { cout << re << " + " << im << "i" << endl; }
};

int main() {
    Complex a(2, 3), b(4, -1), c(1, 2);
    Complex res = a * b + c;
    res.show();
    return 0;
}

Evaluating (2 + 3i) * (4 - i) + (1 + 2i):

  • First, * has higher precedence than +: real = 2*4 - 3*(-1) = 8 + 3 = 11, imag = 2*(-1) + 3*4 = -2 + 12 = 10 -> 11 + 10i.
  • Next, add (1 + 2i): real = 11 + 1 = 12, imag = 10 + 2 = 12 -> 12 + 12i.
Answer:

(2 + 3i) * (4 - i) + (1 + 2i) = 12 + 12i. The C++ program outputs 12 + 12i.

← Objects and ClassesInheritance →