Suggested Const Functions

Hi there,

My first post. I’ve just spent the last ~hr trying to wrap my head around constant functions and objects.

Initially, I thought that the two ‘getters’ were the only two functions that should be constant. But from my understanding (helped profusely by DanM) the reason we want more functions as constants is because of the ability to change Class data, such as the member variables MyCurrentTry and MyMaxTries.

IsGameWon, for example, only needs to check whether or not the game is over; it doesn’t need to change Class data, which for example, could be the integer in int MyCurrentTry. Therefore why leave MyCurrentTry exposed, since IsGameWon WITHOUT const has the power to tap into the member variables…

This is the original code from DanM that sparked my eureka moment:
And for anyone wondering, indenting by 4 spaces allows the coding formatting in these messages (like Stack overflow)

class Person
{
public:
    void NonConstFunction(); //can change class data
    void ConstFunction() const; //can't change class data
private:
    int ID;
    std::string Name;
};

void Person::NonConstFunction()
{
    //both valid
    ID = 4;
    Name = "Bill";
}

void Person::ConstFunction() const
{
    //Not class data; fine to modify
    int FakeID = 3;
    FakeID = 4;
    //attempting to modify class data; invalid
    ID = 10;
    Name = "Jim";
}

As you can see, you can call a constant function (Person::ConstFunction() const) and create local variables inside that function (FakeID) that are completely free to modification. You can’t, however, edit any member variables (ID and Name).

5 Likes

So it took me a bit to get this as well, and reading this post multiple times. Just to make sure I have it straight,

  1. Constant (const) functions (or methods) inside of a class can not change any class variable at all, public or private?
  2. If you put const on all class functions (not saying you always need/want too), the only way to change a class variable is to change the variable itself?

Yes, I believe you’re 100% correct. I wasn’t sure on the public variables, but I just tried creating a variable inside the Public section of the class FBullCowGame and attempting to edit it from a constant function, and it definitely didn’t work.

Thank you for sharing this!!! It really put it into perspective for me. I tested out your statements from the original post and sure enough, IsGameWon() without const can change the MyCurrentTry variable.

For fun I threw BCGame.IsGameWon() function inside the AskToPlayAgain().

Then in FBullCowGame.cpp, under the IsGameWon() function, I changed the MyCurrentTry variable.

As original Devon stated, IsGameWon() has no business modifying MyCurrentTry. Now, once compiled, at first glance everything in the game seems normal…

Unless the player decides to play again XD

So once again, thank you Devon!

Privacy & Terms