It's been a while since I've jumped into C++ but I want to make sure I'm sticking to best practices when I do, including being const-correct.
I'm currently building a library of code for a game framework and I have the following classes (summarised for simplicity):
class Screen
{
public:
Clear();
}
and
class Game
{
private:
Screen* screen;
protected:
const Screen* GetScreen() const;
}
I've omitted the rest for brevity but suffice it to say, the Game
class is responsible for the creation of the Screen
class instance. After it is created, it should only be accessed through the GetScreen()
method.
The idea is, that when creating a new game, I would inherit from this base class, so as an example, during a render loop I would want to clear the screen to redraw the next frame. Now, in my above definitions, the Clear()
method is not allowed to be called when using the GetScreen()
method because it is not const
. The clear method would actually change the internal workings of the class (by virtue of the fact that the previously displayed image is cleared) so that is why I left the const
declaration out of the definition. If I made it const
then I would have to have some of the inner workings of the Screen
class as mutable
but from what I've read, this would not be very const-correct.
So, I have two parts to my question. Should I change void Clear()
to void Clear() const
and make parts of the inner workings mutable
?
Or is the an alternative that would allow me to make the screen
member of the Game
class only settable once by the Game
class so that I can access the non-const member functions during the rest of the program's run time.
Thanks for any help.