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

Recommended Answers

All 4 Replies

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!

ie.

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,

Dave

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.

Daily in the morning, chant out this line " Its better to detect error at compile time than at link time or run time."
And this is the whole key to const-correctness, this is what you call it in technical terms.
Read:http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.1
const-correctness basically ensure type safety. It should be practiced by every efficient programmer. It can sometime saves you hour of work!!

Thank you all for the info...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.