tags:

views:

66

answers:

1

Suppose I define a function in C++ as follows:

void foo(int &x) const {
  x = x+10;
}

And suppose I call it as follows:

int x = 5;
foo(x);

Now typically (without the const keyword), this would successfully change the value of x from the caller's perspective since the variable is passed by reference. Does the const keyword change this? (i.e. From the caller's perspective, is the value of x now 15?)

I guess I'm confused as to what the const keyword does when it is appended to the end of a function definition... any help is appreciated.

+8  A: 

This won't work. You can only const-qualify a member function, not an ordinary nonmember function.

For a member function, it means that the implicit this parameter is const-qualified, so you can't call any non-const-qualified member functions or modify any non-mutable data members of the class instance on which the member function was called.

James McNellis
So does it essentially make `this` a constant within the method? Or is there more to it?
dfetter88
@dfetter88: That's exactly what it does. In a member function that is not const qualified, `this` is of type `T*`. In a member function that is const qualified, `this` is of type `const T*`.
James McNellis
@defetter: There's nothing more to your particular example, since it's ill-formed. Had it been a member function of the form `R function(Args) cv`, the type of `this` is `cv class_type*`. Do you have a [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)?
GMan
Colin
The C++ FAQ handles this: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10.
Oli Charlesworth