←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Operator Overloading & Type Conversion in C++: Unary & Binary

Study material and explanations for Unit 5

Operator Overloading & Type Conversion in C++: Unary & Binary

1. What is Operator Overloading? (In Simple Words)

In C++, regular operators like +, -, and * work naturally with built-in data types like int and float (for example: 5 + 3 gives 8).

However, if you create a Complex number class and try to write:

Complex c3 = c1 + c2;

The compiler gives an error because it doesn’t know how to add two complex objects!

Operator Overloading allows you to give special meaning to existing C++ operators so they can work directly with your own class objects. It is a key part of Compile-Time Polymorphism.

Syntax:

return_type operator symbol (parameters) {
    // Code to perform the operation
}

2. Rules for Operator Overloading (Golden Exam Rules)

  1. Only Existing Operators: You can only overload operators that already exist in C++. You cannot create new symbols like ** or %%.
  2. Precedence Stays the Same: You cannot change the natural priority of operators (* will always be calculated before +).
  3. Cannot Change Operands Count: Unary operators (like ++) must remain unary; binary operators (like +) must remain binary.
  4. Must Involve a Class Object: You cannot change how basic integers work (you cannot redefine int + int).

The 5 Operators that CANNOT Be Overloaded in C++:

(Examiners ask this in almost every exam!)

The 5 Non-Overloadable Operators in C++
1. Dot Operator (.)
Class member access operator.
2. Member Pointer (.*)
Pointer-to-member dereference operator.
3. Scope Resolution (::)
Scope resolution operator.
4. Sizeof Operator
sizeof memory evaluator.
5. Conditional Ternary Operator (?:)
Ternary conditional construct (condition ? true : false).

3. Overloading the Binary + Operator

When overloading a binary operator (like +):

  • As a Member Function: Takes only 1 argument! Why? Because the object on the left calls the function using this, and the object on the right is passed as the argument:
    c1 + c2 becomes c1.operator+(c2)
  • As a Friend Function: Takes 2 arguments (because friend functions have no this pointer):
    c1 + c2 becomes operator+(c1, c2)

Complete Working Code:

#include <iostream>
using namespace std;

class Complex {
    private:
        float real;
        float imag;

    public:
        Complex(float r = 0, float i = 0) {
            real = r;
            imag = i;
        }

        // OVERLOADING THE '+' OPERATOR AS A MEMBER FUNCTION
        Complex operator+(const Complex &c2) const {
            Complex temp;
            temp.real = this->real + c2.real; // Add real parts
            temp.imag = this->imag + c2.imag; // Add imaginary parts
            return temp;
        }

        void display() const {
            cout << real << " + " << imag << "i" << endl;
        }
};

int main() {
    Complex c1(3.5f, 2.5f);
    Complex c2(1.5f, 4.5f);

    // Using the overloaded '+' operator just like normal math!
    Complex c3 = c1 + c2; // Calls c1.operator+(c2)

    cout << "Sum = ";
    c3.display(); // Output: 5 + 7i

    return 0;
}

4. Type Conversion in C++

Sometimes you need to convert between basic data types (like int) and user-defined class objects.

A. Basic Type to Class Type (Using Constructor)

To convert a primitive number (e.g., total minutes = 135) into a Time object (2 hrs 15 mins), write a Single-Argument Constructor:

class Time {
    private:
        int hours, minutes;
    public:
        // Constructor automatically converts int -> Time
        Time(int totalMinutes) {
            hours = totalMinutes / 60;
            minutes = totalMinutes % 60;
        }
        void show() { cout << hours << " hrs " << minutes << " mins" << endl; }
};

int main() {
    int duration = 135;
    Time t1 = duration; // Converts basic int into Time object!
    t1.show();          // Prints: 2 hrs 15 mins
}

B. Class Type to Basic Type (Using Casting Operator)

To convert an object back into a basic primitive type, use a Casting Operator Function:

operator basic_type() {
    return value;
}

Rules: Must be a class member function, has no return type written, and accepts zero parameters.

class Vector {
    private:
        int magnitude;
    public:
        Vector(int m) : magnitude(m) {}

        // CASTING OPERATOR: Converts Vector object -> basic int
        operator int() const {
            return magnitude;
        }
};

int main() {
    Vector v(75);
    int value = v; // Calls operator int()
    cout << "Converted integer: " << value << endl; // Prints: 75
}

DAVV Exam Preparation Tips

Frequently Asked 5-Mark Questions:

  1. List any four rules for operator overloading in C++. Which operators cannot be overloaded?
    Model Answer:
    • Rules: cannot invent new symbols, arity and precedence cannot change, at least one operand must be a class object.
    • 5 non-overloadable operators: ., .*, ::, sizeof, and ?:.
  2. How does binary operator overloading differ between member functions and friend functions?
    Model Answer:
    • Member function takes 1 parameter (left operand is this).
    • Friend function takes 2 explicit parameters because it does not have a this pointer.

Frequently Asked 10-Mark Questions:

  1. Explain the mechanisms of Operator Overloading and Type Conversion in C++. Write a complete program to overload the + operator for complex numbers and demonstrate Basic-to-Class and Class-to-Basic conversions.
    Model Answer:
    • Explain operator overloading syntax and rules.
    • Write out complete code overloading + for class Complex.
    • Explain Basic-to-Class conversion using a 1-parameter constructor.
    • Explain Class-to-Basic conversion using a casting operator (operator int()).