Response to which functions should be const

After getting confused here on classes and const, I decided to break from the course for a day and refer to other resources to clarify the concepts. It helped tremendously, and I think I can answer this challenge with a better understanding of what the program is currently doing.

My understanding is that declaring a class function const means that we do not want the function to modify the value of any associated variables, for example in the video we don’t want GetMaxTries() to modify the MyMaxTries variable (this was also explained by other resources as useful for scientific constants, like the speed of light or gravity).

With this then in mind, and looking at our current set of class functions, I can imagine only Reset() being a const candidate. My reasoning is that the Reset() function would potentially initialize variables in the game to a “clean” (before the game has been played) state, and we don’t want the program to change our initial set of variables for a new instance of the game.

IsGameWon() is boolean, and would necessarily change a variable based on the return value to print a success or loss message. CheckGuessValidity() would also follow this reasoning being a boolean.

I’m not sure how correct this is, but this was my reasoning behind my answers.

IsGameWon doesn’t change the value of a member variable itself though inside the function.

it is actually defined as a const in the code

bool FBullCowGame::IsGameWon() const { return bGameIsWon; }

IsGameWon() is boolean, and would necessarily change a variable based on the return value to print a success or loss message. CheckGuessValidity() would also follow this reasoning being a boolean.

what gets changed in the success/loss message is outside of this isGameWon function. It’s not the result that’s constant, it’s the function that’s constant. i.e. as mentioned above the function doesn’t change anything

you can read const as “this function does not change anything” I think

another example from above code:

int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; }

yes, MyCurrentTry value will change but not in this function. it does not change anything therefore marking it const defines it as such. (It will still work without the const though obviously)

Privacy & Terms