Search

9.2 — Overloading the arithmetic operators

Some of the most commonly used operators in C++ are the arithmetic operators -- that is, the plus operator (+), minus operator (-), multiplication operator (*), and division operator (/). Note that all of the arithmetic operators are binary operators -- meaning they take two operands -- one on each side of the operator. All four of these operators are overloaded in the exact same way.

Overloading operators using friend functions

When the operator does not modify its operands, the best way to overload the operator is via friend function. None of the arithmetic operators modify their operands (they just produce and return a result), so we will utilize the friend function overloaded operator method here.

The following example shows how to overload operator plus (+) in order to add two “Cents” objects together:

This produces the result:

I have 14 cents.

Overloading the plus operator (+) is as simple as declaring a function named operator+, giving it two parameters of the type of the operands we want to add, picking an appropriate return type, and then writing the function.

In the case of our Cents object, implementing our operator+() function is very simple. First, the parameter types: in this version of operator+, we are going to add two Cents objects together, so our function will take two objects of type Cents. Second, the return type: our operator+ is going to return a result of type Cents, so that’s our return type.

Finally, implementation: to add two Cents objects together, we really need to add the m_nCents member from each Cents object. Because our overloaded operator+() function is a friend of the class, we can access the m_nCents member of our parameters directly. Also, because m_nCents is an integer, and C++ knows how to add integers together using the built-in version of the plus operator that works with integer operands, we can simply use the + operator to do the adding.

Overloading the subtraction operator (-) is simple as well:

Overloading the multiplication operator (*) and division operator (/) are as easy as defining functions for operator* and operator/.

Overloading operators for operands of different types

Often it is the case that you want your overloaded operators to work with operands that are different types. For example, if we have Cents(4), we may want to add the integer 6 to this to produce the result Cents(10).

When C++ evaluates the expression x + y, x becomes the first parameter, and y becomes the second parameter. When x and y have the same type, it does not matter if you add x + y or y + x -- either way, the same version of operator+ gets called. However, when the operands have different types, x + y is not the same as y + x.

For example, Cents(4) + 6 would call operator+(Cents, int), and 6 + Cents(4) would call operator+(int, Cents). Consequently, whenever we overload binary operators for operands of different types, we actually need to write two functions -- one for each case. Here is an example of that:

Note that both overloaded functions have the same implementation -- that’s because they do the same thing, they just take their parameters in a different order.

Another example

Let’s take a look at another example:

The MinMax class keeps track of the minimum and maximum values that it has seen so far. We have overloaded the + operator 3 times, so that we can add two MinMax objects together, or add integers to MinMax objects.

This example produces the result:

Result: (3, 16)

which you will note is the minimum and maximum values that we added to cMFinal.

One other interesting thing to note is that we defined operator+(int, MinMax) by calling operator+(MinMax, int). This is slightly less efficient than implementing it directly (due to the extra function call), but keeps our code shorter and easier to maintain (because it reduces duplicate code). It is often possible to define overloaded operators by calling other overloaded operators -- when possible, do so!

9.3 -- Overloading the I/O operators
Index
9.1 -- Introduction to operator overloading

25 comments to 9.2 — Overloading the arithmetic operators

  • akshath

    Learncpp articles were very helpful to me while learning c++.
    In this section why the overloaded artihmetic operators should nor return a reference to the object of class type?I believe lvalues can be assigned to lvalues by implicit conversion to rvalues.thank you

  • pardeep

    thank you very much sir.....
    this site is very helpful to me.

  • dibhar

    Hi Alex,

    Thanks a lot for the tutorials...:)

    having a doubt-

    in the code below if i just remove the keyword friend from the operator function i am getting compilation error :operator+ must take either 0 or 1 argument...why??though we have declared it with two argument...

    #include
    #include
    class Cents
    {
    private:
    int m_nCents;

    public:
    Cents(int nCents) { m_nCents = nCents; }

    // Add Cents + Cents
    Cents operator+(const Cents &c1, const Cents &c2); /*I have removed friend from here*/

    int GetCents() { return m_nCents; }
    };

    // note: this function is not a member function!
    Cents::Cents operator+(const Cents &c1, const Cents &c2)
    {
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
    }

    int main()
    {
    Cents cCents1(6);
    Cents cCents2(8);
    Cents cCentsSum = 4+3+cCents1 + cCents2+5;
    std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;
    getch();
    return 0;
    }

  • mccp13

    Hey Alex,
    Thanks for the tutorials.... I have a question though about the following code. This code compiles properly but i'm wondering why the compiler did not issue an error message when cent2.m_nCents was accessed in the overloaded member function operator+ of myCent1 in main, if the member was private. :

    class Cents
    {
    private:
    m_nCents;
    public:
    //Constructor
    Cents( int nCents ) { m_nCents = nCents; }
    int GetCents(){ return m_nCents; }

    Cents operator+( const Cents& cent2 )
    {
    return Cents( this->m_nCents + cent2.m_nCents );
    }
    };

    int main()
    {
    using namespace std;
    Cents myCent1(6);
    Cents myCent2(8);
    Cents myCent3( myCent1 + myCent2 );
    cout << myCent3.GetCents() << endl;

    return EXIT_SUCCESS;
    }

    btw, i learned this in some OOP book...

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">