What is the meaning of const in declarations like these? The const confuses me.
class foobar
{
public:
operator int () const
https://isocpp.org/wiki/faq/const-correctness#const-member-fns
What is a "
constmember function"?A member function that inspects (rather than mutates) its object.
A
constmember function is indicated by aconstsuffix just after the member function’s parameter list. Member functions with aconstsuffix are called “const member functions” or “inspectors.” Member functions without aconstsuffix are called “non-const member functions” or “mutators.”class Fred { public: void inspect() const; // This member promises NOT to change *this void mutate(); // This member function might change *this }; void userCode(Fred& changeable, const Fred& unchangeable) { changeable.inspect(); // Okay: doesn't change a changeable object changeable.mutate(); // Okay: changes a changeable object unchangeable.inspect(); // Okay: doesn't change an unchangeable object unchangeable.mutate(); // ERROR: attempt to change unchangeable object }The attempt to call
unchangeable.mutate()is an error caught at compile time. There is no runtime space or speed penalty forconst, and you don’t need to write test-cases to check it at runtime.The trailing
constoninspect()member function should be used to mean the method won’t change the object’s abstract (client-visible) state. That is slightly different from saying the method won’t change the “raw bits” of the object’s struct. C++ compilers aren’t allowed to take the “bitwise” interpretation unless they can solve the aliasing problem, which normally can’t be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn’t guarantee that the object won’t change; it merely promises that the object won’t change via that pointer.