How Can Operator Overloading for Multiple Arguments Be Fixed in C++?

  • Context: C/C++ 
  • Thread starter Thread starter waht
  • Start date Start date
  • Tags Tags
    C++ Operator
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 3K views
waht
Messages
1,502
Reaction score
4
I've got an overloaded operator +

Code:
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:
newtype operator+(newtype &A, newtype &B)
{

newtype C;

//more code

return C;

}

Is there something missing?
 
Physics news on Phys.org
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:
Not sure what you are doing but my code compilies fine. I am using 2008 C++ Express edition.

Here is my code.

Code:
#include<cmath>
#include<iomanip>
#include<iostream>

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;
}

Thanks
Matt
 
Yes, const is a must in C++.

Thanks
Matt
 
Woe is me. Const ref works like a charm.