I am very new to programming and I’m now trying to see how constructs work in C++. I know that the order of code affects the output, but in this case I don’t know what’s wrong.
class AddTwoNumbers{
public:
AddTwoNumbers(int a, int b){
SetNumbers(a, b);
}
void SetNumbers(int Number1, int Number2){
Number1 = x;
Number2 = y;
}
int AddNumbers(){
return (x + y);
}
private:
int x;
int y;
};
int main(){
AddTwoNumbers Math(4, 3);
cout << Math.AddNumbers();
return 0;
}
In my head, the construct AddTwoNumbers and the function SetNumbers would be able to update the x and y values so that de AddNumbers function would use the numbers given (4 and 3), but that doesn’t seem to be the case. What should I do to make the AddNumbers function work properly?
>Solution :
What should I do to make the AddNumbers function work properly?
It already works properly.
What doesn’t work properly is the SetNumbers function and through that the constructor. The function has neither return value nor side-effects, so it’s pointless. Furthermore, since x and y are uninitialised when their value is used to assign Number1 and Number2, the behaviour of the program is undefined.
I suspect that you intened to assign x and y instead of assigning Number1 and Number2.