I have class Foo
and its member bar_
is a pointer to some data. Method modify
modifies the data, but not the pointer itself. Therefore I can declare the method as const:
class Foo {
public:
Foo() : bar_(new double) {};
void modify() const {*bar_ += 1;};
private:
double *bar_;
};
If I declare the method as const, it will accessible from other const methods, which is more flexible. At the same time I can drop const as a hint for other developers and users that method modifies the data indirectly (and let think that the data is owned by the class). So I have a choice here: declare modify
as const or drop const: void modify() const
or void modify()
.
What are pros and cons of each approach? What do guidelines say? What should I do?
const
after a method declaration is a statement of intent - const
methods are meant to be idempotent; they do not modify the state of the object and can be called on const
instances.
If the value pointed-to by bar_
is part of the object's state, then a const
method should not modify it.
In addition, even the name modify()
sounds like it modifies the object in some way, and thus should not be declared const
.
But also the other way is important - if a method does not modify the state, it is recommended to declare it const
(see C++ Core Guideline Con.2).