How does C++ handle const marked passed-by-reference classes, that aren't changed directly but from the other side?

Viewed 122

So I am making a Chess Engine right now, and I have a Game class containing an Advantage object, and I am using an odd method to modify them. It involves the Game class calling a member function for the Advantage class, and it passes itself by reference to the Advantage class, and is marked as const. I am now getting some errors that I didn't used to, and decided I didn't really understand fully how this was working. So here's some pseudocode, can someone explain it to me?

class Game ;
class Advantage {
private:
    bool whiteWinning_ = true;
public:
    void updateAdvantage(const Game& game);
}
class Game {
private:
    Advantage advantage_;
    int pawnLocation_ = 1; //obviously, this isn't a real chess game, but still...
public:
    void makeMove(int pawnSteps);
    bool getWinning() const;
}

void Advantage::updateAdvantage(const Game& game){
    //Game is marked const, but the same object is changed because advantage_ is being changed???
    whiteWinning_ = game.getWinning();
}

void Game::makeMove(int pawnSteps) {
    pawnLocation_ += pawnsteps;
    advantage_.updateAdvantage(*this);
}

bool Game::getWinning() const {
    return pawnLocation_ >= 8;
}

1 Answers

The game object which is passed to Advantage::updateAdvantage is casting your argument to const. However the Advantage object in Advantage::updateAdvantage which is denoted as this isn't const, thus allowing you writing to whiteWinning_.

Related