const function what for?

What's the purpose of adding const to a function?


const_iterator begin() const { return data; }


I'm returning data so what's the difference if I ommit const? I don't understand what's used for..
The const keyword is used to mark a thing as “promise not to change its value”.

So, const int x = -7; basically says you are expected to never change the value of x, and the compiler will do its best to hold you to that.

But what about complex types?

1
2
3
4
5
struct point
{
  double x, y;
  double hypotenuse() { return sqrt( x*x + y*y ); }
};

So far, so good. But now you have:

1
2
const point p { 3, 4 };
cout << p.hypotenuse() << "\n";

The compiler will complain. Why? Because that hypotenuse function does not promise not to change p.

Well, it doesn't. So let’s fix the code to make that promise.

1
2
3
4
5
struct point
{
  double x, y;
  double hypotenuse() const { return sqrt( x*x + y*y ); }
};

Now we have a member function that promises not to change its object, and the compiler is happy to let you use it on any point, both const and non-const.

The final thing to remember about this subject is that a non-const object can be temporarily marked as const.

1
2
3
4
5
6
7
8
9
10
void print( const point& p ) // I promise not to change the point I'm referencing here..
{
  cout << p.hypotenuse() << "\n";
}

int main()
{
  point q { 3, 4 };  // q is not const
  print( q );  // but function "print" will treat it as const
}

Hope this helps.
Topic archived. No new replies allowed.