Is private const redundant in a C++ class?

  • A+
Category:Languages

Suppose I have a class with a member variable that I don't want to be changed. Is there any difference between making that variable a private const and just making the variable private, assuming there is no setter function?

Private:

class ConstFoo { public:     Foo(int a);     virtual ~Foo();     int val(){ return val_; } private:     int val_; } 

Private Const:

class ConstFoo { public:     Foo(int a);     virtual ~Foo();     int val(){ return val_; } private:     const int val_; } 

It seems that there is no difference between the two, since you can't change the value of val_ in either case, so the const qualifier seems redundant.

The one reason I can see to explicitly add const is for code clarity, so people working on the code in the future don't add a setter to the function. However, with the name as ConstFoo and documentation specifically stating that it is not meant to be mutable, I don't think this will be an issue.


It's all a matter of how "const" you want this value to be.

As it currently stands, no external user can directly change the value. But they can do so indirectly, because the object itself may not be const:

ConstFoo a{0}; ConstFoo b{2}; a = b; 

a now has 2 in it.

Plus, code within ConstFoo can change its value too; this is why the copy assignment operator can change its value.

So if you want to ensure that the specific member object will assume one value throughout the lifetime of any ConstFoo instance, you declare it const.

Of course, this makes ConstFoo non-assignable.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: