Re: overloading of ","
On 12 Mar, 13:16, Michael DOUBEZ <michael.dou...@free.fr> wrote:
josh a =E9crit :
Hi, I coded the following but It does not return what I expect, why?
#include <iostream>
using namespace std;
class Other
{
public:
int i;
Other(int x=1)
{
i = x;
}
Other *operator-> () { return this;}
Other &operator+ (Other t)
{
i += t.i;
return *this;
}
Other &operator,(Other oth)
{
i = oth.i;
return *this;
}
};
int main()
{
Other o0, o1, o2(4), o3(5);
o0->i = 100;
cout << o0.i << "\n" << o0->i << "\n";
// HERE it returns 5 AND not 6 WHY ???????????????????
Other ox = (o1 + o1, o3 = o2 + o1);
Because you have 5.
The expression evaluates:
Other ox = ( (o1 + o1) , (o3 = o2 + o1) );
Or with names
Other ox = o1.operator+(o1).operator,(o3.operator=(o2.operator+(o1)));
Since o3 is 5, then o1 is also 5 and ox is 5.
The reason is overloaded operator, doesn't have the same precedence as
POD operator,. Is is very confusing.
// ------------------
cout << ox.i << endl;
return 0;
}
Michael
so the compiler is doing:
o1.operator+(01).operator,(03 = 02.operator+(01))
and evaluating it to 5
but when we define overloaded operators the rules "should" be that
they have the same precedence and the same associativity and the same
arity of
the PDO and so really I don't understand why here the rules seems to
be "could"....
Here in the code it seems that it doesn't save the first evaluating
operation on o1...
may be only for the comma operators is there an exception rule????