SkypeMeSM
SkypeMeSM

Reputation: 3287

C++ overloading << with no const for the input object gives error, which goes away with const object

I have the following operator-overloading prototypes:

 ostream& operator<<(ostream & outputstream, my_arr& arr)

 my_arr operator+(const my_arr& left, const my_arr& right)

I call:

 cout << (arr1 + arr2);

This gives me the following compiler error:

error: no match for ‘operator<<’ in ‘std::cout << operator+(const my_array&, const my_array&)((*(const my_array*)(& y)))’

This goes away if I change the signature of << to the following:

  ostream& operator<<(ostream & outputstream, const my_arr& arr)

I might be missing something basic here, but why does this happen? Thanks for your help.

Upvotes: 3

Views: 119

Answers (3)

billz
billz

Reputation: 45410

Because you have a typo in operator+ also you need to pass const my_arr to operator

my_array operator+(const my_arr& left, const my_arr& right)
^^^^ should be my_arr                   ^^^ need to be const

Or you have to overload operator<< for my_array

ostream& operator<<(ostream & outputstream, my_arr& arr)

Otherwise the code just compiles and runs OK: sample link

Upvotes: 1

Yuushi
Yuushi

Reputation: 26040

As has been mentioned, the result of this is a temporary (an rvalue). You can also provide an overload of your output operation which has the form:

ostream& operator<<(ostream& outputstream, my_arr&& arr);

which cout << (arr1 + arr2); will then utilize.

Upvotes: 2

Karel Petranek
Karel Petranek

Reputation: 15154

The problem is that when passing as reference, you cannot pass "temporary" (rvalue) objects such as the result of an addition. When passing a const reference, C++ rules allow passing temporaries because it's guaranteed they won't be written to.

Upvotes: 4

Related Questions