2

Background :

I am working on a toy program (Disclosure : an assignment), where I am required to make a class A having two integer data members. Subsequently, I am to make 3 objects of this class and make a fourth one whose data members hold the sum of the corresponding values from the first 3 objects.

The question itself was simple enough, but I made it a slightly 'fresh' way - I have a method int getIntegerInput() which obtains command line input from the user and returns it. I directly pass said inputs into the class constructor, which uses them to populate the member fields.

However, there was a quirk - the values passed by me are stored in the opposite order to that in which I enter them, messing up my calculation.


MCVE :

The most that I could simplify the code while still preseving the problem behaviour was -

#include <iostream>
using namespace std;

int getIntegerInput();

class A {
    int x;
    int y;

    public :
    A( int xValue, int yValue) {
        (*this).x = xValue; cout << (*this).x;
        (*this).y = yValue; cout <<(*this).y;
    }
};

int main() {
    A a( getIntegerInput(), getIntegerInput() );
    return 0;
}

int getIntegerInput() {
    cout << "Enter a number:\n";
    int x;
    cin >> x;
    return x;
}

An example of the problem behavior :

./a.out
Enter a number:
2
Enter a number:
3
32

Notes :

  1. Tinkering around, I found that both the following codes work fine:

    #include <iostream>
    using namespace std;
    
    int getIntegerInput();
    
    int main() {
        int x, y;
        x = getIntegerInput();
        y= getIntegerInput();
        cout << "x = " << x << "\ny = " << y << "\n";
        return 0;
    }
    
    int getIntegerInput() {
        cout << "Enter a number:\n";
        int x;
        cin >> x;
        return x;
    }
    

Second code.

    #include <iostream>
    using namespace std;

    class A {
        int x;
        int y;

        public:
            int getX() {
                return (*this).x;
            }
            int getY() {
                return (*this).y;
            }

        A(int xValue, int yValue) {
            (*this).x = xValue;
            (*this).y = yValue;
        }
    };

    int main() {
        int x,y;
        cout << "Enter numbers";
        cin >>x;
        cin >>y;
        A a(x,y);
        cout << "x = " << a.getX() << "\ny = " << a.getY() << "\n";
        return 0;
    }
  1. Just in case that's relavant, I am using g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0.
Community
  • 1
  • 1

0 Answers0