What is the meaning of const
in declarations like these? The const
confuses me.
class foobar
{
public:
operator int () const
Blair's answer is on the mark.
However note that there is a mutable
qualifier which may be added to a class's data members. Any member so marked can be modified in a const
method without violating the const
contract.
You might want to use this (for example) if you want an object to remember how many times a particular method is called, whilst not affecting the "logical" constness of that method.
Meaning of a Const Member Function in C++ Common Knowledge: Essential Intermediate Programming gives a clear explanation:
The type of the this pointer in a non-const member function of a class X is X * const. That is, it’s a constant pointer to a non-constant X (see Const Pointers and Pointers to Const [7, 21]). Because the object to which this refers is not const, it can be modified. The type of this in a const member function of a class X is const X * const. That is, it’s a constant pointer to a constant X. Because the object to which this refers is const, it cannot be modified. That’s the difference between const and non-const member functions.
So in your code:
class foobar
{
public:
operator int () const;
const char* foo() const;
};
You can think it as this:
class foobar
{
public:
operator int (const foobar * const this) const;
const char* foo(const foobar * const this) const;
};
when you use const
in the method signature (like your said: const char* foo() const;
) you are telling the compiler that memory pointed to by this
can't be changed by this method (which is foo
here).
The const keyword used with the function declaration specifies that it is a const member function and it will not be able to change the data members of the object.