Search code examples
c++referencesfml

Passing references as function arguments doesn't work


I have code like this(all made for a minimal, reproducible example):

enum class gameState{
Normal,
Special};

class Piece{
public: Vector2i position;
int shape;};

class Board{
public: int array[8][8];
std::vector<Piece> f;
Board() : f(std::vector<Piece>(32)) {}; };

void promotion(int shape, gameState &state, Board &b){
state = gameState::Special;
b.array[b.f[0].position.x][b.f[0].position.y] = shape;
b.f[0].shape = shape;};

And then I try to call them in main:

int main(){
gameState state = gameState::Normal;
Board b;
promotion(1, state, b);
return 0;};

The problem is that it seems to correctly pass by reference for gameState state object, it doesn't modify Board b object, which isn't supposed to happen. How can I correctly pass Board b by reference (or a pointer)?

P.S.: Vector2f is simply a 2D vector the SFML library uses.


Solution

  • Actually, Board in your code is being (CORRECTLY) passed by reference to promotion function. Are you sure it is not changed after function call? What it prints if you do:

    int main(){
        gameState state = gameState::Normal;
        Board b;
        std::cout << b.array[b.f[0].position.x][b.f[0].position.y] <<std::endl;
        promotion(1, state, b);
        std::cout << b.array[b.f[0].position.x][b.f[0].position.y] <<std::endl;;
        return 0;
    };