Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

C++ Operator Overloading

In this tutorial, we will learn about Operator Overloading, different approaches, Rules for Operator Overloading and how to overload Operator with the help of examples.

Overloading

If we Create two or more members that have the same name but are different in number or type of parameter is known as “Overloading” .

In C++, we can overload:

  • Methods
  • Constructors
  • Indexed Properties

We can overload these members because they have parameters only.


Types of Overloading

There are two types of Overloading as follows:

  1. Function Overloading.
  2. Operator Overloading.

In Earlier Tutorials, we already discuss the Function Overloading, In this tutorial we will discuss Operator Overloading.


Operator Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide special meaning to the user-defined data type. Operator overloading is used to overload or redefine most of the operators available in C++. It is used to perform the operation on the user-defined data type.

Using operator overloading in C++, you can specify more than one meaning for an operator in one scope.

For example :- ‘+’ operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc.

Other example :- classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.

The advantage of operator overloading is that it can perform different operations on the same​ operand.


For Example:-

Suppose we have created three objects a1a2 and sum from a class named Complex that represents complex numbers.

Since operator overloading allows us to change how operators work, we can redefine how the + operator works and use it to add the complex numbers of a1 and a2 by writing the following code:

sum = a1 + a2;

instead of something like

sum = a1.addNum(a2);

This makes our code intuitive and easy to understand.

Note: We cannot use operator overloading for fundamental data types like intfloatchar and so on.


Syntax for Operator Overloading in C++

To overload an operator, we use a special operator function.

class className {
    ... .. ...
    public
       return_type operator symbol (argument(s)) {
           ... .. ...
       } 
    ... .. ...
};

Here, is an explanation for the above syntax:

  • return_type is the return type of the function.
  • Next, we mention the operator keyword.
  • symbol is the operator we want to overload. Like: +<-++, etc.
  • argument(s) can be passed to the operator function in the same way as function.

What is the difference between operator functions and normal functions?

Operator functions are same as normal functions. The only differences are, name of an operator function is always operator keyword followed by symbol of operator and operator functions are called when the corresponding operator is used.

Moving on with this article on Operator Overloading in C++.


Types of Overloading approaches

Operator Overloading can be done by using three approaches, they are

  • Overloading unary operator.
  • Overloading binary operator.
  • Overloading binary operator using a friend function.

Operator Overloading in Unary Operators

Unary operators operate on only one operand. The increment operator ++ and decrement operator -- are examples of unary operators.

For Example:-


Example 1: C++ Program to Overload the Unary Operator (++)

#include <iostream>
using namespace std;
class Count {
   private:
    int num;

   public:
    // Constructor to initialize count to 2
    Count() : value(2) {}

    void operator ++ () {
        Count num = num + 2;
    }
    void display() {
        cout << "The Count: " << num << endl;
    }
};
int main() {
    Count c;

    // Call the "void operator ++ ()" function
    ++c;
    c.display();

    return 0;
}

Output

The Count: 4

Example 2: C++ Operator Overloading using Unary Operator

#include <iostream>
using namespace std;
class Count {
   private:
    int value;

   public:
    // Constructor to initialize count to 4
    Count() : value(4) {}

    // Overload ++ when used as prefix
    Count operator ++ () {
        Count test;

        // Here, value is the value attribute of the calling object
        test.value = ++value;

        return temp;
    }
    // Overload ++ when used as postfix
    Count operator ++ (int) {
        Count test;

        // Here, value is the value attribute of the calling object
        test.value = ++value;

        return test;
    }
    void display() {
        cout << "Count: " << value << endl;
    }
};
int main() {
    Count count1, result;

    // Call the "Count operator ++ ()" function
    result = ++count1;
    result.display();

    // Call the "Count operator ++ (int)" function
    result = count1++;
    result.display();

    return 0;
}

Output

Count: 5
Count: 6

Here, we have used the following code for prefix operator overloading:

// Overload ++ when used as prefix
Count operator ++ () {
    Count test;

    // Here, value is the value attribute of the calling object
    test.value = ++value;

    return test;
}

The code for the postfix operator overloading is the same as well. Notice that we have created an object test and returned its value to the operator function.

Also notice the code

test.value = ++value; 

The variable value belongs to the count1 object in main() because count1 is calling the function, while test.value belongs to the test object.


Operator Overloading in Binary Operators

Binary operators work on two operands. For example,

result = num + 9;

Here, + is a binary operator that works on the operands num and 9.

When we overload the binary operator for user-defined types by using the code:

obj3 = obj1 + obj2;

The operator function is called using the obj1 object and obj2 is passed as an argument to the function.


Example 3: C++ Binary Operator Overloading

#include <iostream>
using namespace std;
class A {
    int n;
   public:
   A(){}
    A (int s) {
    n = s;
    }
    void operator + (A);
    void display ();
};
    void :: operator+ (A a) {
        int m = n + a.n;
        cout << "The Result of addition of two objects: " << m << endl;
    }
int main() {
    A a1(5);
    A a2(4);

    a1 + a2;

    return 0;
}

Output

The Result of addition of two objects: 6

Example 4: C++ Program to overload the binary operator and adds two complex numbers

#include <iostream>
using namespace std;
class Complex {
    private:
    float real;
    float imagine;

    public:
    // Constructor to initialize real and imagine to 0
    Complex() : real(0), imagine(0) {}

    void input() {
        cout << "Enter real and imaginary Number respectively: ";
        cin >> real;
        cin >> imagine;
    }

    // Overload the + operator
    Complex operator + (const Complex& obj) {
        Complex test;
        test.real = real + obj.real;
        test.imagine = imagine + obj.imagine;
        return test;
    }

    void output() {
        if (imagine < 0)
            cout << "Output Complex number: " << real << imagine << "i";
        else
            cout << "Output Complex number: " << real << "+" << imagine << "i";
    }
};

int main() {
    Complex complex1, complex2, result;

    cout << "Enter first complex number:\n";
    complex1.input();

    cout << "Enter second complex number:\n";
    complex2.input();

    // complex1 calls the operator function
    // complex2 is passed as an argument to the function
    result = complex1 + complex2;
    result.output();

    return 0;
}

Output

Enter first complex number:
Enter real and imaginary parts respectively: 6 3
Enter second complex number:
Enter real and imaginary parts respectively: 5 4
Output Complex number: 11+7i

In this program, the operator function is:

Complex operator + (const Complex& obj) {
    // code
}

Instead of this, we also could have written this function like:

Complex operator + (Complex obj) {
    // code
}

However,

  • using & makes our code efficient by referencing the complex2 object instead of making a duplicate object inside the operator function.
  • using const is considered a good practice because it prevents the operator function from modifying complex2.

Things to Remember in C++ Operator Overloading

  1. With operator overloading, you can redefine the way an operator works only for the user-defined types (objects, structures). You cannot use it for built-in types (float, char, int, etc.).
  2. Two operators = and & are already overloaded by default in C++. For example, to copy objects of the same class, we can directly use the = operator. We do not need to create an operator function.
  3. Operator overloading cannot change the precedence and associativity of operators. However, if we want to change the order of evaluation, parentheses should be used.
  4. There are 5 operators that cannot be overloaded in C++. They are:
    1. :: scope resolution operator
    2. ?: ternary operator
    3. . member selector
    4. sizeof Operator
    5. * member pointer selector

Rules for Operator Overloading

Here are the rules for Operator Overloading:

  • For it to work, at least one operand must be a user-defined class object.
  • You can only overload existing operators. You can’t overload new operators.
  • Some operators cannot be overloaded using a friend function. However, such operators can be overloaded using member function.
Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!