Specific functions that should use Const

All “Getter” methods should make use of the “const” suffix to ensure all “getter methods” cannot change private member variables and fulfill only what they are designed to do; get information that already exists. This guarantees the scope of the function is enforced and limits how the function can be manipulated.

With the above said, the other function that should have a const on the end is the, “BCGame.getCurrentTry()” function.

Taking a stab in the dark, but would we, in main.cpp, write int MaxTries = BCGame.GetMaxTries(); as const int MaxTries = BCGame.GetMaxTries(); and then the same for int CurrentTry?

Don’t take my comment for truth but I don’t think so! Also sorry, this will be a long post but your question got me thinking and I wanted to answer and make it clear to myself as well! :stuck_out_tongue:

Saving a variable as const in main would not have the same effect as having a const function as all it does is ensure that the parameter that you create and save the value in (MaxTries ex) doesn’t change while running main. This of course can be what we want, but it is not necessary to add just because the function we get the value from is const.

Setting a function to const in a class is to make sure that the information we have on the current object doesn’t change just from running its own member functions (at least the getter functions).
Take his previous example in the lectures about the factory (the class) and the cars ( the objects created from the class). Some cars can be created with their lights off, right? If we were to run the “GetLights const” function we would not want the lights to randomly turn on before getting the result back, we want information about the object without having it change in the process. Having it set to const makes sure that this doesn’t happen.

Writing const int Lights = SomeCar.GetLights() in main however, would save the variable Lights as off (assuming GetLights is const) and then not allowing the variable Lights to change for the remainder of the main.
Had Lights been used in a loop for example, looping through a large amount of cars this would not work, since the lights of the first car is saved permanently and the lights of the any other car could not change the constant value ( I don’t believe the compiler would allow this to run in the first place anyway)

So saving something as a constant variable in main is absolutely something we may want on occation, but it doesn’t have to be related to a function declared as const in a class.

2 Likes

That does make sense! Hindsight is always frustrating too. After watching further videos into the lesson, and reading up on LearnCPP.com, I see why that would not be the most efficient solution.
Thanks for the in-depth feedback Emelie!

Privacy & Terms