Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

final

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++?

like image 755
Matthias Ronge Avatar asked Sep 09 '16 12:09

Matthias Ronge


1 Answers

You have to place the const at the right place in the declaration. The rule is: const applies to the thing immediately to the left, unless it's at the left edge itself, when it applies to the right.

Therefore, these two are (mutable) pointers to a constant integer:

const int * p;
int const * p;

This is a constant pointer to a (mutable) integer:

int * const p;

And these are constant pointers to a constant integer:

const int * const p;
int const * const p;
like image 117
Angew is no longer proud of SO Avatar answered Nov 15 '22 05:11

Angew is no longer proud of SO