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.