What is the difference between
void showDist() const {
}
and
void showDist() {
}
and what is the benefit of const
here?
What is the difference between
void showDist() const {
}
and
void showDist() {
}
and what is the benefit of const
here?
const
says that you will not modify any of the member variables of the object (or more correctly *this
). Note that this
is not the same as const this
. const
pointers and non-const
pointers are incompatible.
If you have a const
object, you must provide a const overload.
class Foo
{
public:
// Remove this and see the compiler error
void foo() const
{
std::cout << "Const.";
}
void foo()
{
std::cout << "Non-const.";
}
};
int main(int argc, char* argv[])
{
const Foo foo;
foo.foo();
}
Consider a class X
.
The only difference is:
In a non-const
member function, the type of this
is:
X*
In a const
member function, the type of this
is:
const X*
That's it.
Because of this, the const
member function
X
except for the members that are mutable
.const
member function of the class X
.