Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My C++ code that uses a construct to sum 2 numbers always outputs 16

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading