Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Operator overloading C++

  1. Sep 12, 2009 #1
    I've got an overloaded operator +

    Code (Text):

    newtype X, Y, Z, W;

    W = X + Y;  // works fine

    W = Y + X; // works fine

    // but with more arguments I'm getting compiler error

    // saying there is no match for operator+

    W = X + Y + Z;

    Sample code
    Code (Text):

    newtype operator+(newtype &A, newtype &B)

    newtype C;

    //more code

    return C;

    Is there something missing?
  2. jcsd
  3. Sep 12, 2009 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Just eyeballing it, I agree with the compiler.

    Temporary objects cannot be implicitly converted to modifiable references -- the standard doesn't allow it, and even if it did, you shouldn't do it anyways because it can lead to all sorts of really, really hard to debug problems.

    Since X+Y is a temporary value, it cannot be converted into the modifiable reference required by your operator+.

    Now, the fix is actually very easy: write operator+ correctly! The arguments almost certainly should not be modifiable references -- they should be const references.

    (Well, technically there are occasions where you're better off without using references at all)
    Last edited: Sep 12, 2009
  4. Sep 12, 2009 #3
    Not sure what you are doing but my code compilies fine. I am using 2008 C++ Express edition.

    Here is my code.

    Code (Text):

    int x,y,z,w,pause;  // needed variables

    using namespace std;

    int main()
        x = 1;
        y = 2;
        z = 3;

        w = x+y;
        w = y+x;
        w = x+y+z;

        cout << w << endl;
        cin >> pause; // dummy input to keep the output screen visible

        return 0;
  5. Sep 12, 2009 #4

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Even if "your code compiles fine" does not mean it is right. Besides, per your first post, your code does not compile fine. It doesn't even compile, period. I would not call that "fine".

    Make the arguments to newtype operator+ be const references and then it will be fine.
  6. Sep 12, 2009 #5
    Yes, const is a must in C++.

  7. Sep 12, 2009 #6
    Woe is me. Const ref works like a charm.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook