Reputation: 11998
In this below program I have overloaded commaoperator. But, why comma operator
is not taking considering the first element/object
.
class Point {
int x, y;
public:
Point() {}
Point(int px, int py)
{x = px;y = py;}
void show() {
cout << x << " ";
cout << y << "\n";
}
Point operator+(Point op2);
Point operator,(Point op2);
};
// overload comma for Point
Point Point::operator,(Point op2)
{
Point temp;
temp.x = op2.x;
temp.y = op2.y;
cout << op2.x << " " << op2.y << "\n";
return temp;
}
// Overload + for Point
Point Point::operator+(Point op2)
{
Point temp;
temp.x = op2.x + x;
temp.y = op2.y + y;
return temp;
}
int main()
{
Point ob1(10, 20), ob2( 5, 30), ob3(1, 1);
Point ob4;
ob1 = (ob1, ob2+ob2, ob3);//Why control is not reaching comma operator for ob1?
ob1 = (ob3, ob2+ob2, ob1);//Why control is not reaching comma operator for ob3?
ob4 = (ob3+ob2, ob1+ob3);//Why control is not reaching comma operator for ob3+ob2?
system("pause");
return 0;
}
I have tried to understand ,
operator also but could not able to find the solution.
ob1 = (ob1, ob2+ob2, ob3);//Why control is not reaching comma operator for ob1?
ob1 = (ob3, ob2+ob2, ob1);//Why control is not reaching comma operator for ob3?
ob4 = (ob3+ob2, ob1+ob3);//Why control is not reaching comma operator for ob3+ob2?
Any help appreciated.
Upvotes: 5
Views: 199
Reputation: 16338
You should never change the semantics of the operators you're overloading. The comma operator evaluates the left expression, executes any side effects, discards the result, then evaluates the second and returns the evaluated result (and type).
Upvotes: 1
Reputation: 254751
Why control is not reaching comma operator for ob1?
I guess you're asking, why does this line only output two points: 10 60
for ob2+ob2
, and 1 1
for ob3
. This is because you only invoke the comma operator twice; each time, it outputs its right-hand argument and ignores its left-hand argument.
The line of code is equivalent to
ob1.operator,(ob2+ob2).operator,(ob3);
making it clear that it's only called twice. ob1
is evaluated, but the operator doesn't do anything with it.
Upvotes: 5
Reputation: 55425
ob1 = (ob1, ob2+ob2, ob3);//Why control is not reaching comma operator for ob1?
It does, you just didn't do anything to notice it.
You defined the operator as a member function. Now let's rewrite the expression above, ignoring the left side of assignment operator:
(ob1.operator,(ob2+ob2)).operator,(ob3);
// ^^^^^^^^^^^^^^^^^^
// displays contents of ob2+ob2
// ^^^^^^^^^^^^^^
// displays contents of ob3
Or equivalent, but easier to understand:
{
Point temp = ob1.operator,(ob2+ob2);
temp.operator,(obj3);
}
Upvotes: 2
Reputation: 51920
It does reach it. But since you're only printing out the values of the argument of operator,
and never of this
, you don't get to see it printed out.
Upvotes: 2