0

What is the difference between

void showDist() const { 
} 

and

void showDist() {
}

and what is the benefit of const here?

2 Answers2

2

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();
}
0

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

  1. isn't allowed to modify any member of the class X except for the members that are mutable.
  2. isn't allowed to call any non-const member function of the class X.
Sam
  • 1,842
  • 3
  • 19
  • 33