There is a class A
and it has the following operator()
implementation:
void A::operator()(...parameters...) const
{
// operator body
}
What does this const
mean?
There is a class A
and it has the following operator()
implementation:
void A::operator()(...parameters...) const
{
// operator body
}
What does this const
mean?
Methods in C++ can be marked as const
like in the above example to indicate that the function does not modify the instance. To enforce this, the this
pointer is of type const A* const
within the method.
Normally, the this
pointer within a method is A* const
to indicate that we cannot change what this
points to. That is, so that we cannot do this = new A()
.
But when the type is const A* const
we also cannot change any of the properties.
That the method uses this
as a const A*
and then can only call other const
methods.
See this entry of the CPP FAQ.
As already amply described, it means that the method will not modify the observable state of the object. But also, and very importantly, it means the method can be called on a const object, pointer, or reference - a non-const method cannot. ie:
class A
{
public:
void Method1() const
{
}
void Method2()
{
}
};
int main( int /*argc*/, char * /*argv*/ )
{
const A a;
a.Method1(); //ok.
a.Method2(); //compiler error!
return 0;
}
const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called.
It means that calling the operator will not change state of the object.
A const
member function promises to not change the observable state of the object.
Under the hood, it might still change state, e.g. of mutable
members. However, mutable
members should never be visible from anywhere outside the class' interface, i.e. you should never attempt to lie to client code, because client code may validly expect that const
functions don't tweak the object's outer hull. Think of mutable
as an optimization tool (e.g. for caching and memoization).
Example for mutability:
You have a quadtree class. Under the hood, the quadtree is build up lazily, i.e. on demand; this lazyness is hidden from users of the class. Now, a query-method on that quadtree should be const
, because querying a quadtree is expected to not change the quadtree. How do you implement const-correctness and lazyness without breaking C++' rules? Use mutable
. Now you have a quadtree that for the user looks const, but you know that under the hood, there's still a lot of change:
class Quadtree {
public:
Quadtree (int depth);
Foo query (Bar which) const;
private:
mutable Node node_;
};