const type qualifier soon after the function name

Vijay picture Vijay · Aug 13, 2010 · Viewed 13.9k times · Source

In C++ sometimes I see declarations like below:

return_type function_name(  datatype parameter1, datatype parameter2  ) const
{ /*................*/}

What does this const type qualifier exact do in this case?

Answer

Drew Hall picture Drew Hall · Aug 13, 2010

The const qualifier at the end of a member function declaration indicates that the function can be called on objects which are themselves const. const member functions promise not to change the state of any non-mutable data members.

const member functions can also, of course, be called on non-const objects (and still make the same promise).

Member functions can be overloaded on const-ness as well. For example:

class A {
  public:
    A(int val) : mValue(val) {}

    int value() const { return mValue; }
    void value(int newVal) { mValue = newVal; }

  private:
    int mValue;
};

A obj1(1);
const A obj2(2);

obj1.value(3);  // okay
obj2.value(3);  // Forbidden--can't call non-const function on const object
obj1.value(obj2.value());  // Calls non-const on obj1 after calling const on obj2