Home > Mobile >  Different value after fuction call
Different value after fuction call

Time:12-15

I have a class

class player{
private:
    int x;//coordinates
    int y;
public:
    player() {}
    player(int px, int py) {
        x = px;
        y = py;
    }
    int get_x() {
        return x;
    }
    int get_y() {
        return y;
    }

and a class avatar that inherit from class player:

class avatar :public player {

public:
    avatar() {}
    avatar (int px, int py) :player (px, py) {
        cout << "Make a avatar in this coordinates" << " " << px << " " << py << endl;
    }

I do

void start(avatar &av){
    .
    .
    .
    .
    .
    (in the end of the fuction)
    cout << endl << avatar .get_x() << ", " << avatar.get_y();
}

int main()
    avatar pl;
    start(pl);
    cout << endl << player.get_x() << ", " << player.get_y();

and the results i am getting are

6, 8(right answer) -858993460, -858993460(after the function,wrong answer)

i dont understand why that happen. I use by reference function call(&)

CodePudding user response:

There are many errors in the code you have shown.

But, the most important mistake that can cause the behavior you are experiencing is that you are default constructing an avatar object in main(), but neither of your default constructors in player or avatar are initializing the x and y data members, so they will have indeterminate values. That is why you see garbage in your output.

You need to initialize x and y, eg:

class player{
private:
    int x;
    int y;
public:
    player() : x(0), y(0) {} // <-- HERE
    ...
};

Alternatively:

class player{
private:
    int x;
    int y;
public:
    player(int px = 0, int py = 0) { // <-- HERE
        x = px;
        y = py;
    }
    ...
};

Otherwise, you need to construct the avatar object in main() with initial values, eg:

int main()
    avatar pl(6, 8);
    ...
}
  • Related