≡ Menu

How to Use C++ Operator Overloading with an Example Program

Operator overloading is one of the advanced concepts of C++.  It is a feature through which most of the standard operators can be used with class objects.

When you use an expression like ‘2 +3’, you know that the answer will be the sum of two integers. This is because the compiler knows how to interpret the + operator when used with integers. But, what if you want to do something like ‘obj1 = obj2 + obj3’ (where all these are objects of same class) ? How + operator should work in this case?

The answer is through Operator Overloading.

In this tutorial, we will explain operator overloading with the help of a working example.

Note that operator overloading is different from function overloading.

Operator Overloading in C++

Consider the following class :

class example
{
public:
    int a;
    int b;
};

What I want to do is to create three objects of this class and assign the sum of two of these objects to the third one i.e. something like this :

example obj1, obj2, obj3;

    obj1.a = 1;
    obj1.b = 1;

    obj2.a = 2;
    obj2.b = 2;

    obj3.a = 0;
    obj3.b = 0;

    obj3 = obj1 + obj2;

When I say that I want to add objects, I want corresponding integer members to added. For example, something like this :

obj3.a = obj1.a + obj2.a;
obj3.b = obj1.b + obj2.b

This is what exactly can be done through operator overloading. Observe the single line in bold above, the operator + and = are being used. So we need to overload these operators in order to achieve exactly what is represented in the above two lines.

Now, the question arises, how to overload the operators? Well, here is declaration of an overloaded operator + for class example:

 example operator+(const example& obj);

This declaration should be made part of class example. Similarly, we can overload = operator.

On a related note, it is also important for you to understand C++ virtual functions and references in C++.

A C++ Operator Overloading Working Example

If you have understood the concept till now, here is a full fledged working program that demonstrates operator overloading :

#include <iostream>
class example
{
public:
    int a;
    int b;
    example operator+(const example& obj);
    void operator=(const example& obj);
};

void example::operator=(const example& obj)
{
    (*this).a = obj.a;
    (*this).b = obj.b;

    return;
}

example example::operator+(const example& obj2)
{
    example tmp_obj = *this;
    tmp_obj.a = tmp_obj.a + obj2.a;
    tmp_obj.b = tmp_obj.b + obj2.b;
    return tmp_obj;
}

int main(void)
{
    example obj1, obj2, obj3;

    obj1.a = 1;
    obj1.b = 1;

    obj2.a = 2;
    obj2.b = 2;

    obj3.a = 0;
    obj3.b = 0;

    obj3 = obj1 + obj2;

    std::cout<<obj3.a<<"  "<<obj3.b<<"\n";

    return 0;
}

In the example above :

  • When ‘obj1 + obj2’ is encountered, function corresponding to overloaded  operator + is called. You can think of ‘obj1 + obj2’ as something like ‘obj1.add(obj2)’. The function corresponding to overloaded operator + is called in context of obj1 and hence only obj2 is needed to be passed as argument. obj1 can be accessed through ‘this’ pointer in that function.  Here in this function, individual integer member is added and the resultant object is returned.
  • Similarly, every thing happens the same way when the resultant object of the sum of obj1 and obj2 is assigned to obj3 through overloaded = operator. Each integer member of class is assigned to corresponding member of obj3.

Here is the output of this program :

$ ./op_ovr
3  3

So we see that the + and = operators worked exactly in the similar way as they work for standard types. Through operator overloading the code becomes relatively neat and easy to maintain.

Exception to Operator Overloading

Though most of the operators can be overloaded, there are certain operators that can not be overloaded. Here is the list of those operators :

  • dot (.) operator
  • sizeof operator
  • Scope resolution (::) operator
  • Arithmetic if (?:) operator
  • (.*) operator
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Muralidhara MK September 26, 2013, 1:19 am

    thegeekstuff articles are really useful. Could you provide any good understanding article on DNP3 Protocol.

  • Bob September 26, 2013, 9:43 am

    Cool. Thanks for the refresher.

  • SeattleC++ September 26, 2013, 12:48 pm

    This example doesn’t fully illustrate the powerful results achievable with operator overloading. If you overload *all* the arithmetic operators, and provide the right constructors, you get a class that is interchangeable with an int or a double. For instance, if you want a number type like int, but which throws an exception on overflow, you can do that. If you want to create a rational number or a fixed-point number. You can do that.

  • Tri September 26, 2013, 12:52 pm

    Clear & precise explanation.

  • Romano September 27, 2013, 6:43 pm

    This example does help for those who are learning c++.
    Keep it up and don’t stop in writing c++ article.
    Best wishes!!

  • Girishkumar September 29, 2013, 3:20 am

    Very good..
    you should add example for ++ (or –) operater as it has wo types: pre-increment and post-increment.

  • Dustin La Ferney October 1, 2013, 8:43 am

    A very useful feature. Just used this in a lab assignment to add fraction objects to either integers, or other fraction objects. It required the + operator to be further overloaded to accept an object reference as a parameter rather than just an integer. The end result was a much more visually pleasing and understandable block of code.

  • DuskoKoscica October 2, 2013, 7:30 am

    Overloading operators make my day every time I us it.

    But somehow, I am not so sure that you could overload all of the opperators. Before it was problem for ++ the prefix and sufix, but you have the dummy operator.
    Did not hear that it could be done with just all of them.

    Is it me, or C++11

  • SeattleC++ October 2, 2013, 10:54 am

    You can overload all the numeric operators, logical operators, comparison operators; in otherwise anything that takes values and produces values.

    There are several other symbols that behave something like operators, but take a name, rather than an object, as their right operand. They include member access (.), deference pointer to class member (.*), scope resolution (::), size of (sizeof). These cannot be overloaded because their meanings are too deeply wired into the compiler.

    The conditional operator (?:) also cannot be overloaded. I don’t know why.

    The point of overloading operators is mostly to make new numerical types like rational numbers, and to allow a natural syntax for operations on vectors or matrices. It can be used to recycle the operator symbols for non-arithmetical use (it is traditional, for example, to overload the ‘+’ operator for string concatenation). But except for traditions in wide use, overloading arithmetical operators for non-arithmetical use is very confusing, so it is not good practice.

  • duskoKoscica October 3, 2013, 5:48 am

    Yeah, I know like that, but from statements before it was not so obvious.

    Also, there is a big problem about something like…. templates.
    Well, the variadic templates are very good thing.

  • raheel October 29, 2013, 5:41 am

    very nice concept

  • compor July 21, 2014, 12:50 am

    in this case it might be fine since a and b are non-pointer primitives,
    but aren’t you supposed to check for self-assignment?
    also, should op= return a ref to *this in order to allow chaining of =,
    as in:
    o1 = o2 =o3;

    which is natural and expected behaviour from that operator?

  • duskoKoscica August 1, 2014, 11:29 am

    @compor.
    The overload operator should have been done differently.

  • sorath October 6, 2014, 12:34 am

    thank you this for this it clear my concept about operator overloading but there is still some questions in my mind would you please give me ans of those?
    Q 1: How poly morphism is related to operator over loading ?
    Q 2: how operators work as member function and as non-member function?

  • duskoKoscica October 7, 2014, 11:55 am

    Q1 is very easy, it is about friends function that could be used for <> for example. For question one it is hard to get the right answer. Polimorphism it means that you would have more apearences of one method or something, and for overloading it would be using operator somethin, so you could have two methods with different data types for example. But, you could have templates, so you would not worry about question one. Have nice day

  • Sanjay July 20, 2015, 8:28 pm

    Thank U admin ….
    This one is very very easy ways to the poor student like me to be clear in each and every matter….
    Hope to see ur note ever in future too
    Once again, thank U

  • Anonymous January 9, 2016, 8:50 am

    excellent explanation

  • Michael January 12, 2016, 4:18 am

    You don’t explain: Similarly, we can overload = operator.
    I think there is more to it. Can you write an article about that?

  • Sagor Chandro March 24, 2016, 11:49 am

    It was very helpful.
    Thanks a lot and please keep writing such helping articles

  • Shilpa January 31, 2017, 8:10 am

    Nice notes it is helpful.. But c if u can overload =