What is the meaning of const
in declarations like these? The const
confuses me.
class foobar
{
public:
operator int () const
The const
qualifier means that the methods can be called on any value of foobar
. The difference comes when you consider calling a non-const method on a const object. Consider if your foobar
type had the following extra method declaration:
class foobar {
...
const char* bar();
}
The method bar()
is non-const and can only be accessed from non-const values.
void func1(const foobar& fb1, foobar& fb2) {
const char* v1 = fb1.bar(); // won't compile
const char* v2 = fb2.bar(); // works
}
The idea behind const
though is to mark methods which will not alter the internal state of the class. This is a powerful concept but is not actually enforceable in C++. It's more of a promise than a guarantee. And one that is often broken and easily broken.
foobar& fbNonConst = const_cast(fb1);