c++ – Const keyword appended to the end of a function definition… what does it do? – Education Career Blog

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;

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.


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.

Leave a Comment