Paramaeleon Paramaeleon - 3 months ago 11
C++ Question

How to define a final variable (mutable constant) in C++?

How do I define a constant in C++, that points to a mutable object?

If I declare

static const CMyClass* IMPL;


and assign

const CMyClass* CSomeClass::IMPL = new CMyClass;


then I can only call
const
functions on the object. Its internals are locked. This is not what I want.

If I leave off the
const
qualifier, I can reassign the pointer
IMPL
, so it isn’t protected as a constant anymore, which it should be.
final
seems to be applicable only to functions in C++. Is there an equivalent to a Java’s
final
variables in C++?

Answer

Solution

class CMyClass{};

class CSomeClass{
    static CMyClass* const IMPL;
};

CMyClass* const CSomeClass::IMPL = new CMyClass;

Explanation

const in C++ is not the exact analog of Java's final.

  • In Java the final specifier applies to the variable and means that the variable cannot be reassigned (though the object referred to by that variable can still be modified).

  • Unlike that, in C++ const applies to the type. Since C++ has pointers it is important to distinguish the type of the pointer variable itself and the type of the object to which that variable would refer. Depending on where you put your const it applies to the former or the latter. The other answers elaborate on that in more detail.