Paramaeleon Paramaeleon - 1 year ago 135
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
functions on the object. Its internals are locked. This is not what I want.

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

Answer Source


class CMyClass{};

class CSomeClass{
    static CMyClass* const IMPL;

CMyClass* const CSomeClass::IMPL = new CMyClass;


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download