MockExams

Unary/Binary Operator Overloading, Stream Insertion/Extraction & Type Conversions

AI draft, not yet reviewedUnit 6: Operator OverloadingAbout 2 minutes

Idea in plain words

Operator Overloading gives user-defined types natural syntactic operators (+, -, *, ==, <<).

Exam tip

High-yield exam topic (Very High).

Explanation

Operator overloading transforms user-defined classes into first-class mathematical types without changing operator precedence or associativity. When overloading binary operators as member functions, the left operand is implicitly *this and the right operand is passed as an argument. Overloading via friend functions is necessary to support commutative operations where a primitive appears on the left (e.g., 5 + myObject).

Key points

  • Operators that CANNOT be overloaded: . (member access), .* (pointer-to-member), :: (scope resolution), ?: (ternary conditional), sizeof.
  • Prefix vs Postfix ++/--: Prefix takes no argument (operator++()); Postfix takes a dummy int argument (operator++(int)).
  • Overloading stream operators: operator<< and operator>> MUST be overloaded as friend functions because the left-hand operand is an ostream/istream reference.
  • Type Conversions: (1) Basic to Class type (via single-argument constructor), (2) Class to Basic type (via operator type() conversion function), (3) Class to Class type.

Example

Example

Class to Basic type conversion: operator float() const { return sqrt(xx + yy); }. Vector2D v(3, 4); float mag = v; // Evaluates to 5.0.

Code examples

// Overloading Binary + and Stream Insertion <<
#include <iostream>
using namespace std;

class Vector2D {
private:
    float x, y;

public:
    Vector2D(float x = 0, float y = 0) : x(x), y(y) {}

    // Overloading binary + as member function
    Vector2D operator+(const Vector2D &other) const {
        return Vector2D(this->x + other.x, this->y + other.y);
    }

    // Overloading prefix ++
    Vector2D& operator++() {
        ++x; ++y;
        return *this;
    }

    // Overloading postfix ++
    Vector2D operator++(int) {
        Vector2D temp = *this;
        x++; y++;
        return temp;
    }

    // Overloading << as friend function
    friend ostream& operator<<(ostream &out, const Vector2D &v) {
        out << "(" << v.x << ", " << v.y << ")";
        return out;
    }
};

Exam questions

  • [8 Marks] Overload the stream insertion (<<) and extraction (>>) operators for a Matrix or Complex number class in C++.
  • [7 Marks] Differentiate between prefix and postfix increment operator overloading with code examples.
  • [7 Marks] Explain data conversion routines: (i) Basic to Class type, (ii) Class to Basic type, (iii) Class to another Class type with examples.

BIT154CO

Switch Course

On this page

Past Exam Questions

Not asked in past exams yet

This topic hasn't appeared in previous exam papers.

Search BIT154CO

Reading

Theme
Reading mode
Text size
Default
Font
Line width
Line spacing