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).