How do I change the value in the class? (C ++)
I'm just trying to add or subtract from a value in a class from the main file, but it seems to always reset that value to zero . As a newbie, I really don't understand why ?! Every time I type player.worldPositionY it says either -1, 1, or 0 (if neither 1 or 2 is selected - moveForward or moveBack)
I have two simple files, Main.cpp:
#include <iostream>
#include "player.h"
using namespace std;
int keyboardInput;
int main()
{
Player player;
cin.get();
cin >> keyboardInput;
if (keyboardInput == 1){
player.moveForward();
} else if (keyboardInput == 2){
player.moveBack();
}
cout << "Y: " << player.worldPositionY << endl;
main();
}
And player.h:
class Player {
public:
int worldPositionY = 0;
void moveForward();
void moveBack();
};
void Player::moveForward(){worldPositionY += 1;}
void Player::moveBack(){worldPositionY -= 1;}
I am clearly missing something. Please, help!
source to share
You are calling main
recursively. You don't want to do this, do this instead:
int main()
{
Player player;
while (true)
{
cin.get();
cin >> keyboardInput;
if (keyboardInput == 1){
player.moveForward();
} else if (keyboardInput == 2){
player.moveBack();
}
cout << "Y: " << player.worldPositionY << endl;
}
}
Calling main
recursively means that your object is player
recreated every time you enter a value, so your values ββwere always either -1
or 1
.
source to share
The problem is that every time you call main()
, the object is created again with a default null value. Now you can do like @cmbasnett mentioned in his> or you can do worldPositionY
static
like
class Player {
public:
static int worldPositionY; // making it static
void moveForward();
void moveBack();
};
int Player::worldPositionY=0; // don't forget to initialize it outside as well.
source to share