Language Selector

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
9.1 -- Introduction to operator overloading

47 comments to 9.2 — Overloading the arithmetic operators

  • Tom

    Hello Alex -

    A. Two typos:

    1. “When the operator does not modify its operands”

    2. “Finally, implementation: to add two Cents objects together”

    B. If instead of:

    we had:

    that would break the logic of the code (it would still return 3,16 instead of 2,25). How would you handle it? Like this maybe?:

    • Thanks for the edits. As for point B, that’s actually an interesting concern. If possible, it’s always a good idea to think about how the user might misuse a class -- and if there’s a reasonable way to handle it, then do so. In this case, your suggestion is perfect -- if the user passes in the min and max in the wrong order to the constructor, we can detect that and flip them.

  • minwei

    Hi, can demostrate a example for me on how(1,2,3,4) + (2,3,4,5) using operator overloading. I dun reali understand the example given

  • Kinten

    Hi alex, I have a dobout when you call

    you actually create a Cents object in the “cCents1 + cCents2” part and then it is copied to cCentsSum, however in the case that you allocate a dinamic variable whit new, when you call the “cCents1 + cCents2” part, the object will never go out of scope, and you will have a memory leak, I am right?

    Another thing, when you do the

    part, its the = operator always overloaded to copy every member variable of a class?

    Tnx, -Kin-

    • Yes, objects declared with new have to be deleted, otherwise the memory is lost and you have a memory leak. In this case, since we aren’t using new, that isn’t an issue we have to worry about.

      The compiler supplies every class with a default implementation of operator=, which copies each member variable.

      • Alex H

        Sooo…. What do you do when you DO use 'new'? Been wrestling with this for weeks because I'm making my own String class.

        Say I have this command "str1 = str2 + str3"

        If you change your op + to return, say, a String by reference (String&) and return an unnamed object, then the object ends up getting destroyed before the op = fires. If you don't return by reference, then you end up with a nice fat memory leak.

        How the heck to do you work around that? Add an extra parameter to your op = to know whether or not it was called after an op + so that it can delete the temp string?

  • M.N. Jayaram


    I copied the code for Cents class example (the second one with two overloaded + operators) & the MinMax class to the clipboard & pasted it to my Code::Blocks IDE.

    The compiler flags the “No match for operator+ …..” error in lines 32 and 33 of the Cents example & line 56 in the MinMax example.

    Both the examples run successfully when the reference is removed i.e. pass by value as below

    friend Cents operator+(Cents cCents, int nCents);
    friend Cents operator+(int nCents, Cents cCents);

    friend MinMax operator+(MinMax cM1, MinMax cM2);
    friend MinMax operator+(MinMax cM, int nValue);
    friend MinMax operator+(int nValue, MinMax cM);

    What could be the reason ?

    P.S. : The example code runs as is in Visual C++ 6.0 without the above mentioned changes that I had to do to get Code::Blocks to run the example.

    • I believe it has to do with the way the different compilers handle references to intermediary objects. I fixed up the example by making all the reference parameters const references, as they should have been in the first place. I think it should work without error now.

  • M.N. Jayaram


    I have an observation. Instead of having many versions of overloading the operators with different combos it should be sufficient to have one version of operator to do Objects & use type conversion to handle other types. Otherwise the no. of combos of operators may become too unwieldy.

    Thus, the Cents & MinMax examples work with minimal operator versions as below.

    • This is true, and is a great observation. The one major downside of doing it this way is that it is about half as efficient since you have to do the extra step of converting to a temporary object before producing your final result. Whether efficiency or additional maintainability is a larger concern depends on the nature of the class and project. Never-the-less, thanks for the great point.

    • Miguel

      Hi all,

      Note that the code above does not work when the programmer use template class instead (cf. for deatils):

      This code makes the g++ compiler complaining about operator+ :

      The programmer shall explicitly define the operator+ (as Alex has done in its example).

      The Jayaram suggestion is nice, but it implies some magics from compiler.

      The advantage that I see from the Alex code sample is that there is no magic, making code clearer and allow the programmer changing a non template class into template class without surprise :)

    • Matt

      I don’t understand how your code works with respect to the addition at the end. To me it looks like that single parameter Minmax would handle the ints so it would treat them like a class where both the min and the max were the same value. I never see a function call to that though so how does your program know how to treat the addition (no pun intended) of intends along with that of classes?

  • Jay

    You might want to explain why the operators should be a friend function instead of a member function and therefore breaking encapsulation.

  • Lucky

    Hi Alex,
    I am really confused with this operator overloading concept. Especially I dont understand y shoul
    d we use a friend class. In the example discussed above

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

    A.Y r we using call by reference??
    B.What happens in Main when

    Cents cCentsSum = cCents1 + cCents2;

    is encountered/

    • A lot of times we use friend classes when doing operator overloading because it makes the functions easier to write.

      Remember that a member function always has to have an implicit data type that is pointed to by *this. Thus, if you do something like this:

      , the compiler translates that to a.add(b). a becomes the implicit data type. Now we have a as an implicit type, and b as an explicit type. This can be awkward.

      However, if we use a friend function, then both a and b come through as parameters, which makes the functions easier to write because we don’t have to worry about any implicit variables.

      In this case, we use call by reference because we don’t want to copy the Cents class to do a pass-by-value. Really, those should be const references.

      • Hi Alex, Is it still good coding if we just have the operators as member functions, I’ve only started and it appears easier for me to have everything inside the class.

        Also in light of using friend functions and manageability where do you recommend I keep them (the friend functions). Just below my class, like your example, or somewhere else?


  • mahen

    Hi Alex,
    In the first example in this page… u passed the cents objets by reference …since they are objects, arent they passed by reference implicitly?…… y did u explicitly pass them by reference ?….

  • thabukkow

    Why do you use a reference as a parameter:

    it works the same when I use this:

    I also changed the declaration of the friend function

    • Seven_Hong

      Got confused too, hope Alex could answer this.

    • Nathan

      The advantage is covered in the section on passing by reference.

      Here’s a recap: Your modified declaration passes the MinMax instances by value, which requires creating additional copies in memory. For larger classes, this can cause a large amount of overhead and risk a stack overflow. It is a good general rule to pass user-defined objects by reference as a way to avoid these risks.

  • Dominator_X

    friend MinMax operator+(const MinMax &cM1, const MinMax &cM2);

    What does &cM1? Please reply! Can you explain in more detail.

  • 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
    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…

  • 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…

    class Cents
    int m_nCents;

    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;
    return 0;

    • Nathan

      By making the function a member function, the function that you have declared has 3 arguments: Cents* const this, const Cents &c1, and const Cents &c2. Since operator+ is a binary operator, it must have 2 parameters.

      An updated version that Works On My Machine (TM):

  • pardeep

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

  • 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

  • Max

    In this example…

    using namespace std;

    class Cents
    int m_nCents;

    Cents(int nCents) { m_nCents = nCents; }

    // Overload cCents + int
    friend Cents operator+(const Cents &cCents, int nCents);

    // Overload int + cCents
    friend Cents operator+(int nCents, const Cents &cCents);

    int GetCents() { return m_nCents; }

    // note: this function is not a member function!
    Cents operator+(const Cents &cCents, int nCents)
    return Cents(cCents.m_nCents + nCents);

    // note: this function is not a member function!
    Cents operator+(int nCents, const Cents &cCents)
    return Cents(cCents.m_nCents + nCents);

    int main()
    Cents c1 = Cents(4) + 6;
    Cents c2 = 6 + Cents(4);
    std::cout << "I have " << c1.GetCents() << " cents." << std::endl;
    std::cout << "I have " << c2.GetCents() << " cents." << std::endl;

    return 0;
    …it's not clear to me how the expression Cents(4)+6 is evaluated. Yeah I know that we're overloading operator "+" for operands of types Cents and int respectively.
    As I understand Censt(4) is the constructor, right? So when…
    Cents operator+(const Cents &cCents, int nCents)
    return Cents(cCents.m_nCents + nCents);
    …is called does cCenst become a reference to Cents(4)?
    From the line…
    return Cents(cCents.m_nCents + nCents);
    …one can deduce that cCenst is an object of type Censt since we access m_nCents via member selection operator "." But Censt(4) is a constructor and not a class object.
    To me it doesn't make sense for cCenst to be a reference to Cents(4) since they're not equivalent.

  • nice meme

    how does MinMaxs constructor evaluate this expression and put 3 into min member and 16 into max member

    MinMax cMFinal = cM1 + cM2 + 5 + 8 + cM3 + 16;

    did i miss something about anonymous class objects?? can someone please someone could step by step this evaluation

  • Adam


    In my "practice code" I have created a relatively simple "Words" class meant to take in some strings.

    In it I have tried to overload the + operator (and made it a friend function) in order to join strings as follows:

    wherein two strings would be concatenated.

    This works for assignments such as:

    This absolutely refuses to work for:

    At first I thought it was due to (cWord1+cWord2) resolving to an anonymous variable, but I don’t think that is the reason.

    Is there something fundamental that I am misunderstanding?

    Thank you very much for the information on the website in general - extremely useful.


  • "Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++"

    Extracted from "Constructors part II". If it is illegal, why you called the constructor from a friend function which is almost a member function???

    Isn’t it illegal????? Or MinMax is only written for making sure that the evaluated value would be a MinMax?

    • Alex

      In older versions of C++, a constructor cannot call another constructor (this restriction was lifted in C++11).

      This isn’t directly calling a constructor: it’s explicitly creating an object of type MinMax (which will indirectly call a constructor).

      What we’re doing here is essentially the same as:

      Just without the temporary variable.

  • vish

    #include <iostream>
    using namespace std;

    class Calc
        int mval;
        Calc(int a){mval=a;
       friend Calc operator+(Calc &a,int &b);
       friend Calc operator+(int &a,Calc &b);
       int geta(){return mval;
    Calc operator+(Calc &a,int &b){
        return Calc(a.mval+b);
    Calc operator+(int &a,Calc &b){
        return Calc(a+b.mval);

      Calc a = Calc(2)+5;

    what is wrong with it?

    • Alex

      Your function

      should be one of these:

      It’s failing because you’re trying to add the literal 5, and you can’t pass a literal to a non-const reference. Your int parameter either needs to be pass by value or pass by const reference in order to accommodate literals.

  • Quang

    I dont get this lesson ?!
    - Why do you use Cents as a type when you declare operator+
    _ Can you show me how does operator+ works in main in the first example

    Thank you so much Alex!

    • Alex

      We’re declaring an overloaded operator+ that takes two Cents objects and returns a Cents object that represents the sum.

      So when we do this:

      The compiler evaluates cCents1 + cCents2, and looks for an overloaded operator+ function to add them (which it finds, because we wrote it). The function returns a temporary Cents value, that’s copied back into cCentsSum.

      • Quang

        I now get it Alex, thank you!
        1 more struggle: how can you do this: Cents c1 = Cents(4) + 6;
        Shouldnt it be like : Cents test ( 4 );
                              Cents c1 = test +6; ?

        • Alex

          Great question!

          C++ compilers are smart. When the compiler sees something like this:

          First it looks to see if there’s an overloaded operator+ that takes a Cents and an int parameter. In this case, there isn’t. But it does see that there’s an overloaded operator+ that takes a Cents and a Cents parameter. So the next question it asks is whether the int can be implicitly converted into a Cents. Because we’ve provided a constructor that takes an int, the answer is yes! So, the 6 gets converted into Cents(6), and the overloaded operator+ that adds two Cents gets called.

          Pretty clever if you ask me.

          • Rahul

            Alex, in my program

            This line works, even if operator+ is not defined for these type of parameters and constructor is NOT declared as ‘explicit’.

            But, below line gives and error

            Here the implicit conversion of 10 to Cents(10) is not taking place when operator+ is not defined and presence of explicit keyword to constructor doesn’t matter.

            Please throw some light on this.

            • Alex

              I’m not sure why this would work. I tried this on Visual Studio 2015 and neither line compiled.

              As defined, there’s no conversion between a Cents and an int (since we haven’t overloaded the int typecast), so I’m not sure how it would know how to convert c2 into an int to add it.

            • Rahul

              It was a const keyword in operator+ that takes a Cents and a Cents as parameter. Have a look.

            • Alex

              I think what may be happening here is that the compiler is noting that there’s a function that can add two Cents, so it looks to see if an integer can be converted into a Cents object. It can, since there’s a Cents(int) constructor. Thus, the compiler creates an anonymous Cents object from the integer and passes it to operator+.

              However, this only works if the operator+ has const parameters, since you can’t have a non-const reference to a temporary/anonymous object. Similarly, if the function is marked as explicit, the compiler won’t do the conversion from int to Cents.

  • Sasuke

    Hi Alex
    Thank you for this great tutorials ^_^
    just a question about the last paragraph
    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)

    if we use inline for this function
    inline MinMax operator+(const MinMax &cM, int nValue);

    is our program efficient like implementing it directly ?

    sorry about my English

  • Gopal

    In the last example minMax, we are not doing any arithmetic addition, instead we are keeping track of minimum and maximum values seen so far. In this case we overloaded + operator to keep track of minimum and maximum values of Objects.

    This means we can overload operators to do any task not just only arithmetic operation. Am i correct?

    • Alex

      Yes. If you want to change the meaning of an operator for your specific class, you can (though it’s generally not recommended unless the updated meaning is fairly natural). Just keep in mind that you can not change the operator’s precedence.

Leave a Comment




4 × 3 =

Put C++ code inside [code][/code] tags to use the syntax highlighter