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
here. This is up to you to decide. – Pelletmutable
members thatconst
functions can modify. Whether or not a function should beconst
really depends on whether it is "logically const" - doesn't modify the object in any meaningful observable way. – Furunculosis