Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Only Allow a member variable to be set once
    primarykey
    data
    text
    <p>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.</p> <p>I'm currently building a library of code for a game framework and I have the following classes (summarised for simplicity):</p> <pre><code>class Screen { public: Clear(); } </code></pre> <p>and</p> <pre><code>class Game { private: Screen* screen; protected: const Screen* GetScreen() const; } </code></pre> <p>I've omitted the rest for brevity but suffice it to say, the <code>Game</code> class is responsible for the creation of the <code>Screen</code> class instance. After it is created, it should only be accessed through the <code>GetScreen()</code> method.</p> <p>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 <code>Clear()</code> method is not allowed to be called when using the <code>GetScreen()</code> method because it is not <code>const</code>. 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 <code>const</code> declaration out of the definition. If I made it <code>const</code> then I would have to have some of the inner workings of the <code>Screen</code> class as <code>mutable</code> but from what I've read, this would not be very const-correct.</p> <p>So, I have two parts to my question. Should I change <code>void Clear()</code> to <code>void Clear() const</code> and make parts of the inner workings <code>mutable</code>?</p> <p>Or is the an alternative that would allow me to make the <code>screen</code> member of the <code>Game</code> class only settable once by the <code>Game</code> class so that I can access the non-const member functions during the rest of the program's run time.</p> <p>Thanks for any help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload