When checking my code with PC-LINT it advised me to make some member-functions const
What is the advantage of doing this ?

I do it just to remind myself (and the compiler) that no class variables can be changed in this function. Basically just to keep me from accidentally doing something stupid!


double YourClass::GetX()
  x_ = 2.0;

You should not be modifying any of the member variables in a get function! But the compiler doesn't know that, unless you do this:

double YourClass::GetX() const
  x_ = 2.0;

Then it will give you an error, because you are not allowed to modify x_ from this function!

Hope that helps,


const is a 'promise' not to change.

If you have member-functions that do not change your class (and never should) you can declare them const.

const member-functions are declared like this:

int getValue() const;

The primary purpose for const member-functions is that they are the only member-functions you can call for a const reference to that class.

Functions that need to be able to look at a class but do not need to change it should declare the parameter as a const reference.

class Sample;
int myfunc(Sample const & data)

Inside myfunc (above) the only member-functions of data that can be called are the const member-functions.

This question has already been answered. Start a new discussion instead.