The code below, which is giving a correct output of the addition, changes x value of the first object b after doing it.
class numbers{
public:
int x;
numbers(int i1){
x = i1;
}
numbers operator+ (numbers num){
x = x + num.x;
return(x);
}
};
int main(){
numbers a (2);
numbers b (3);
numbers c (5);
numbers d (7);
cout << a.x << b.x << c.x << d.x << endl; // returns 2357
numbers final (100); //this value won't be shown
final = a+b+c+d;
cout << a.x << b.x << c.x << d.x << endl; // returns 5357
cout << final.x; //returns 17 (2+3+5+7)
system("pause");
}
The question is, how does this addition class works exactly? I mean, why is x from object a modified?
I though only x from final object would be modified.
Thanks 🙂
The call to operator+ is just like any other member function call.
a + btranslates toa.operator+(b). So the linex = x + num.x;in this case is actually assigning toa.x. To achieve what you want you need to instead populate a new numbers with the new value i.e.Also note the const – which would have given you a compile error when you made that mistake.