Search code examples
javac++constantsoverridingfinal

In C++, is there a way I can make a mutable const member variable? Like with the "final" keyword in java?


I'm creating a game engine class which will have a "logger" member. Like this:

class Engine {
public:
    const Logger logger;
    Engine();
    ~Engine();

    void init();
    void start();
};

My question is whether it's possible to make "logger" so I can't override the variable, but still modify the object itself?


Solution

  • C++ has no concept of "replacing" variables in the first place, so what you're asking for doesn't make a ton of sense. It would be better to forget Java when writing C++; they are different languages with different paradigms and concepts.

    If you want to prevent users of your class from being able to logically "replace" it wholesale, the closest thing to that in C++ is the = operator. This actually just calls the operator= function on the existing object, though conventionally we typically implement that function to copy all the state from one to another, so from a very high-level perspective it could be considered a similar thing.

    If you don't want people to be able to do that, make operator= be deleted (or private) in Logger. Now there is not even the imaginary concept of being able to "replace" it. Keep its instance non-const and every other usage remains accessible.

    If it helps, imagine that your class Engine doesn't contain a Logger, but instead a Logger* pointing to some dynamically-allocated object. If it were a Logger* const then the pointer would not be permitted to later point elsewhere, though the pointee (the Logger itself) would remain mutable. This is the closest thing to Java's reference semantics and final that I can muster for this example. However I caution against needless dynamic allocation: use this option for mental comparison purposes only!