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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

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.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

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 +.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

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.

Looking to accelerate your career as a skilled Full Stack Web Developer? Leverage Caltech CTME's academic excellence in a unique bootcamp-style Post Graduate Program in Full Stack Web Development. Enroll Now!

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.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.