In this article, we are going to learn about one of the important properties of object-oriented programming concepts known as operator overloading. C++ programming language enables the programmer to have more than one execution behavior for a function or an operator within the same scope. In OOPS, overloading refers to having the same name but with different purposes. Typically, there are two types of overloading in C++. They are function overloading and operator overloading. When a function or an operator is overloaded, the compiler must decide which function or operator is being called in the present situation by checking the parameters and operands. This approach to selecting a suitable function or an operator is called Operator Resolution. Let us have more ideas about each one of them in the next sections.

Function Overloading in C++

Functional Overloading is a property where two or more functions can share the name but not the same list of arguments. It is one of the salient features of C++. Function overloading can also be treated as compile-time polymorphism. Upon a keen observation, the name remains the same whereas the order, data type, and entire list of arguments change. Let us look at an example of function overloading in C++.

Example:

#function1

void addPodium(int a, int b)

{

cout << a + b;

}

#function2

float addPodium(float a, float b, float c)

{

return (a + b + c);

}

In the above example, we can observe that there are two functions being defined as a piece of code where the name of functions remains same as “addPodium” but the return type and the list of input arguments and their data types have been changed.

What Is Operator Overloading in C++?

Similar to function overloading, OOPS enables the extra facility to overload some of the inbuilt operators present in C++. An operator can be overloaded by placing a keyword ‘operator’ just before the operator symbol. Let us understand by an example:

// C++ program to overload the binary operator +

// This program adds two complex numbers

#include <iostream>

using namespace std;

class Complex {

   private:

    float real;

    float imag;

   public:

    // Constructor to initialize real and imag to 0

    Complex() : real(0), imag(0) {}

    void input() {

        cout << "Enter real and imaginary parts respectively: ";

        cin >> real;

        cin >> imag;

    }

    Complex operator + (const Complex& obj) {

        Complex temp;

        temp.real = real + obj.real;

        temp.imag = imag + obj.imag;

        return temp;

    }

    void output() {

        if (imag < 0)

            cout << "Output Complex number: " << real << imag << "i";

        else

            cout << "Output Complex number: " << real << "+" << imag << "i";

    }

};

int main() {

    Complex complex1, complex2, result;

    cout << "Enter first complex number:\n";

    complex1.input();

    cout << "Enter second complex number:\n";

    complex2.input();

    result = complex1 + complex2;

    result.output();

    return 0;

}

In the above example, we can observe that the programmer is trying to add two complex numbers along with their real and imaginary parts respectively. The + operator was overloaded such that whenever an addition operation is applied in between two objects then the corresponding action takes place depending upon the redefining of the + operator.

Overloadable/Non-overloadable Operators

Here is the list of some of the overloadable and non-overloadable operators:

+

-

*

/

%

^

&

|

~

!

,

=

<

>

<=

>=

++

--

<<

>>

==

!=

&&

||

+=

-=

/=

%=

^=

&=

|=

*=

<<=

>>=

[]

()

->

->*

new

new []

delete

delete []

Here is the list of non-overloadable operators. They are:

  1. :: scope operator
  2. .* pointer operator
  3. .  dot notation
  4. ?: ternary operator

Operator Overloading Examples

Let us have a look some of the operator overloading examples:

#include <iostream>

using namespace std;

class Test {

int value;

public:

void get_Data() {

cout << "Enter a value : ";

cin >> value;

}

void print_Data() {

cout << value << endl;

}

void operator -() { 

value = -value;

}

};

int main() {

Test t;

t.get_Data();

cout << "Before change the value is : ";

t.print_Data();

-t; // It will call like t.operator -();

cout << "After change the value is : ";

t.print_Data();

}

Output:

Enter a value : 101

Before change the value is : 101

After change the value is : -101

Syntax for C++ Operator Overloading

We have seen earlier that to overload any operator, one should place the keyword ‘operator’ before the operator symbol. Let us understand the structured syntax for C++ operator overloading.

class className {

    ... .. ...

    public

       returnType operator symbol (arguments) {

           ... .. ...

       } 

    ... .. ...

};

Make sure that the indentation is followed and the operator overloading is done within the scope of the class. Here, the return type is the return type of the function, an operator is a keyword, a symbol is any inbuilt operator which is overloadable and arguments are the input to the function.

Operator Overloading in Unary Operators

A unary operator is applied on a single operand. For example, ++, - - are some of the unary operators present in C++. Let us have a look at the operator overloading in unary operators.

Example1: ++ Operator (Unary Operator) Overloading

#include <iostream>

using namespace std;

class Count {

   private:

    int value;

   public:

    Count() : value(5) {}

    void operator ++ () {

        ++value;

    }

    void display() {

        cout << "Count: " << value << endl;

    }

};

int main() {

    Count count1;

    ++count1;

    count1.display();

    return 0;

}

In the above example, whenever ++ is called along with a variable, it increases the value by 1 unit.  In this example, ++ is used as a prefix or pre-increment.

Example 2: ++ Operator (Unary Operator) Overloading

#include <iostream>

using namespace std;

class Count {

   private:

    int value;

   public:

    Count() : value(5) {}

    void operator ++ () {

        ++value;

    }

    void operator ++ (int) {

        value++;

    }

    void display() {

        cout << "Count: " << value << endl;

    }

};

int main() {

    Count count1;

    count1++;

    count1.display();

    ++count1;

    count1.display();

    return 0;

}

In the above example, whenever ++ is called along with a variable, it increases the value by 1 unit.  In this example, ++ is used as a suffix or post-increment.

Example 3: Return Value from Operator Function (++ Operator)

#include <iostream>

using namespace std;

class Count {

   private:

    int value;

   public

       :

    Count() : value(5) {}

    Count operator ++ () {

        Count temp;

        temp.value = ++value;

        return temp;

    }

    Count operator ++ (int) {

        Count temp;

        temp.value = value++;

        return temp;

    }

    void display() {

        cout << "Count: " << value << endl;

    }

};

int main() {

    Count count1, result;

    result = ++count1;

    result.display();

    result = count1++;

    result.display();

    return 0;

}

In the above example, whenever ++ is called along with a variable, it increases the value by 1 unit.  In this example, ++ is used as both pre and post-increment proposes.

Operator Overloading in Binary Operators

There are different types of binary operators in C++ typically used for addition, subtraction, and so on. A binary operator takes two operands as inputs and returns a result. Let's have look at Operator Overloading of binary operators in C++.

Example 4: C++ Binary Operator Overloading

// C++ program to overload the binary operator +

// This program adds two complex numbers

#include <iostream>

using namespace std;

class Complex {

   private:

    float real;

    float imag;

   public:

    // Constructor to initialize real and imag to 0

    Complex() : real(0), imag(0) {}

    void input() {

        cout << "Enter real and imaginary parts respectively: ";

        cin >> real;

        cin >> imag;

    }

    Complex operator + (const Complex& obj) {

        Complex temp;

        temp.real = real + obj.real;

        temp.imag = imag + obj.imag;

        return temp;

    }

    void output() {

        if (imag < 0)

            cout << "Output Complex number: " << real << imag << "i";

        else

            cout << "Output Complex number: " << real << "+" << imag << "i";

    }

};

int main() {

    Complex complex1, complex2, result;

    cout << "Enter first complex number:\n";

    complex1.input();

    cout << "Enter second complex number:\n";

    complex2.input();

    result = complex1 + complex2;

    result.output();

    return 0;

}

In the above example, we can observe that the programmer overloaded a binary operator +.

Things to Remember in C++ Operator Overloading

Let us see some things to remember in C++ operator overloading.

  1. In C++, the = and & are overloaded as default. 
  2. Precedence and associativity of operators don’t get affected due to operator overloading. 
  3. Always remember the point that four operators cannot be overloaded. They are the ternary operator, scope resolution operator, member selection operator, and member selection through a pointer to function operator.

What Is the Difference Between Operator Functions and Normal Functions?

We often see different types of functions being used by programmers. We also came across the operator's functions, recursive functions, and so on. There is a significant difference between the regular normal function and the operator function. The operator functions are similar to regular functions, but the name of the operator function always starts with the keyword ‘operator’ and a symbol that is being overloaded.

Conclusion

Hope this article was able to give you a thorough understanding about operator overloading in C++. If you are looking to further enhance your software development skills, we would recommend you check Simplilearn’s Post Graduate Program in Full Stack Web Development. This course, designed in collaboration with Caltech CTME, can help you gain the relevant knowledge and make you job-ready in just 6 months.

If you have any questions or queries, feel free to post them in the comments section below. Our team will review and get back to you at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449

Learn from Industry Experts with free Masterclasses

  • Learn to Develop a Full-Stack E-Commerce Site: Angular, Spring Boot & MySQL

    Software Development

    Learn to Develop a Full-Stack E-Commerce Site: Angular, Spring Boot & MySQL

    25th Apr, Thursday9:00 PM IST
  • Fuel Your 2024 FSD Career Success with Simplilearn's Masters program

    Software Development

    Fuel Your 2024 FSD Career Success with Simplilearn's Masters program

    21st Feb, Wednesday9:00 PM IST
  • Mean Stack vs MERN Stack: Which Tech Stack to Choose in 2024?

    Software Development

    Mean Stack vs MERN Stack: Which Tech Stack to Choose in 2024?

    9th May, Thursday9:00 PM IST
prevNext