Lesson 19 +35 XP

Operator Overloading: Unary & Binary Operators

Operator Overloading: Unary & Binary Operators

C++ lets user-defined types behave like built-in ones. With operator overloading we can write c3 = c1 + c2; for two complex numbers, or -v for a vector, instead of calling add(c1, c2). The operator keeps its usual syntax, but its meaning is defined for our class. This is another form of compile-time polymorphism.

1. Defining an Overloaded Operator

An operator is overloaded by writing a special function called an operator function:

return-type class-name :: texttt{operator} op (argument-list) { dots }

operator is a keyword and op is the operator being overloaded (+, -, ==, ++ and so on).

An operator function must be either a member function (non-static) or a friend function. The difference shows in the number of arguments:

OperatorAs a member functionAs a friend function
Unary (-x, ++x)no argumentone argument
Binary (x + y)one argument (the right operand)two arguments

A member function needs one argument fewer because the left operand is the object that calls the function (passed implicitly through this).

ExpressionMember function callFriend function call
-xx.operator-()operator-(x)
x + yx.operator+(y)operator+(x, y)
x == yx.operator==(y)operator==(x, y)

Steps to overload an operator

  1. Create a class for the type the operator will work on.
  2. Declare the operator function operator op() in the public part of the class, as a member or a friend.
  3. Define the operator function to do the required work.

2. Overloading Unary Operators

A unary operator acts on one operand. Overloaded as a member function, it takes no arguments and works on the calling object.

Unary minus

C++
#include <iostream>
using namespace std;

class Space {
    int x, y, z;

public:
    Space(int a, int b, int c) {
        x = a;
        y = b;
        z = c;
    }
    void display() {
        cout << x << " " << y << " " << z << endl;
    }
    void operator-(); // unary minus: no argument
};

void Space::operator-() {
    x = -x;
    y = -y;
    z = -z;
}

int main() {
    Space S(10, -20, 30);
    cout << "S  : ";
    S.display();
    -S; // calls S.operator-()
    cout << "-S : ";
    S.display();
    return 0;
}

Output:

OUTPUT
S  : 10 -20 30
-S : -10 20 -30

This version changes S itself. A version that returns a new negated object, Space operator-() const, lets you write T = -S; without changing S.

Prefix and postfix increment

++ has two forms. To tell them apart, the postfix version takes a dummy int argument that is never used.

FormDeclaration (member)Returns
Prefix ++cCounter operator++()the object after incrementing
Postfix c++Counter operator++(int)a copy of the object before incrementing
C++
#include <iostream>
using namespace std;

class Counter {
    int count;

public:
    Counter() {
        count = 0;
    }
    Counter(int c) {
        count = c;
    }
    int get() {
        return count;
    }

    Counter operator++() { // prefix: increment, then return
        ++count;
        return Counter(count);
    }
    Counter operator++(int) { // postfix: the int is a dummy
        Counter old(count);   // remember the old value
        count++;
        return old; // return the value before incrementing
    }
};

int main() {
    Counter c1, c2;
    cout << "c1 = " << c1.get() << ", c2 = " << c2.get() << endl;
    ++c1;
    ++c1;
    c2 = ++c1; // prefix: c2 gets the new value
    cout << "after c2 = ++c1: c1 = " << c1.get() << ", c2 = " << c2.get() << endl;
    c2 = c1++; // postfix: c2 gets the old value
    cout << "after c2 = c1++: c1 = " << c1.get() << ", c2 = " << c2.get() << endl;
    return 0;
}

Output:

OUTPUT
c1 = 0, c2 = 0
after c2 = ++c1: c1 = 3, c2 = 3
after c2 = c1++: c1 = 4, c2 = 3

3. Overloading Binary Operators

A binary operator overloaded as a member takes one argument: the right-hand operand. The left-hand operand is the calling object.

Adding two complex numbers

C++
#include <iostream>
using namespace std;

class Complex {
    float real, imag;

public:
    Complex() {
        real = 0;
        imag = 0;
    }
    Complex(float r, float i) {
        real = r;
        imag = i;
    }
    Complex operator+(Complex c); // binary +: one argument
    Complex operator-(Complex c);
    Complex operator*(Complex c);
    void display() {
        cout << real << " + j" << imag << endl;
    }
};

Complex Complex::operator+(Complex c) {
    Complex temp;
    temp.real = real + c.real; // real is the left operand's, c.real the right's
    temp.imag = imag + c.imag;
    return temp;
}

Complex Complex::operator-(Complex c) {
    return Complex(real - c.real, imag - c.imag); // nameless temporary object
}

Complex Complex::operator*(Complex c) {
    // (a + jb)(c + jd) = (ac - bd) + j(ad + bc)
    return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}

int main() {
    Complex C1(2.5, 3.5), C2(1.6, 2.7), C3;
    C3 = C1 + C2; // C1.operator+(C2)
    cout << "C1      = ";
    C1.display();
    cout << "C2      = ";
    C2.display();
    cout << "C1 + C2 = ";
    C3.display();
    C3 = C1 - C2;
    cout << "C1 - C2 = ";
    C3.display();
    C3 = Complex(1, 2) * Complex(3, 4);
    cout << "(1 + j2)(3 + j4) = ";
    C3.display();
    return 0;
}

Output:

OUTPUT
C1      = 2.5 + j3.5
C2      = 1.6 + j2.7
C1 + C2 = 4.1 + j6.2
C1 - C2 = 0.9 + j0.8
(1 + j2)(3 + j4) = -5 + j10

How C3 = C1 + C2 calls the member operator functionHow C3 = C1 + C2 calls the member operator function

In C3 = C1 + C2, the object C1 calls operator+, and C2 is passed as the argument c. Inside the function, real means C1.real and c.real means C2.real. The result is built in temp and returned, then assigned to C3.

Comparing objects: relational operators

C++
#include <iostream>
using namespace std;

class Distance {
    int feet;
    float inches;

public:
    Distance(int f, float i) {
        feet = f;
        inches = i;
    }
    float total() const {
        return feet * 12 + inches;
    }
    bool operator<(const Distance& d) const {
        return total() < d.total();
    }
    bool operator==(const Distance& d) const {
        return total() == d.total();
    }
    Distance operator+(const Distance& d) const {
        int f = feet + d.feet;
        float i = inches + d.inches;
        if (i >= 12.0f) {
            i = i - 12.0f;
            f++;
        }
        return Distance(f, i);
    }
    void show() const {
        cout << feet << "'-" << inches << "\"";
    }
};

int main() {
    Distance d1(5, 9.5), d2(6, 3.0), d3(4, 21.5);
    Distance sum = d1 + d2;
    d1.show();
    cout << " + ";
    d2.show();
    cout << " = ";
    sum.show();
    cout << endl;
    cout << "d1 < d2  : " << (d1 < d2) << endl;
    cout << "d1 == d3 : " << (d1 == d3) << endl;
    return 0;
}

Output:

OUTPUT
5'-9.5" + 6'-3" = 12'-0.5"
d1 < d2  : 1
d1 == d3 : 1

4. Overloading the Assignment Operator =

The compiler supplies a default operator= that copies member by member (a shallow copy). A class that owns heap memory needs its own operator= that performs a deep copy, checks for self-assignment, frees the old memory, and returns *this so that a = b = c works.

C++
#include <iostream>
#include <cstring>
using namespace std;

class Text {
    char* s;

public:
    Text(const char* t) {
        s = new char[strlen(t) + 1];
        strcpy(s, t);
    }
    Text(const Text& o) {
        s = new char[strlen(o.s) + 1];
        strcpy(s, o.s);
    }
    ~Text() {
        delete[] s;
    }

    Text& operator=(const Text& o) {
        if (this != &o) {                  // 1. guard against a = a
            delete[] s;                    // 2. free the old buffer
            s = new char[strlen(o.s) + 1]; // 3. deep copy
            strcpy(s, o.s);
        }
        return *this; // 4. allow a = b = c
    }
    void show() const {
        cout << s << endl;
    }
};

int main() {
    Text a("first"), b("second"), c("third");
    a = b = c; // chained assignment
    a = a;     // self-assignment is safe
    a.show();
    b.show();
    c.show();
    return 0;
}

Output:

OUTPUT
third
third
third
💡 Tip

Key points to remember

  • Operator function: return-type operator op(args); it must be a member or a friend.
  • Member: unary takes 0 arguments, binary takes 1 (the left operand is this). Friend: unary 1, binary 2.
  • Postfix ++/ - take a dummy int argument; prefix returns the new value, postfix the old value.
  • C1 + C2 means C1.operator+(C2).
  • A class owning memory needs operator= with a self-assignment check, a deep copy and return *this.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is operator overloading? Write a program to overload the binary + operator to add two complex numbers. (10 Marks)
  • Write: the definition and syntax, the member vs friend argument table, the Complex program with output, and the explanation of C1.operator+(C2).
  • Q2. Write a program to overload the unary minus operator. (5 Marks)
  • Write: the Space program with output.
  • Q3. How are prefix and postfix increment operators distinguished when overloading? Write a program. (5 Marks)
  • Write: the dummy int rule, the table, and the Counter program.
  • Q4. Why does a member operator function for a binary operator take only one argument? (2.5 Marks)
  • Q5. Overload = for a class with dynamic memory. Why is the self-assignment check needed? (5 Marks)