aPoC aPoC - 6 months ago 35
C++ Question

What is meant with "const" at end of function declaration?

Possible Duplicate:

Meaning of “const” last in a C++ method declaration?

I got a book, where there is written something like:

class Foo
int Bar(int random_arg) const
// code

Also, a by-the-way question: why should/shouldn't I use
before argument declarations? What does that change ?

int Foo (const int Bar) { /* code */ }

So if I do now:

Foo v1, v2;

Will the (const-tagged) Bar function exist 3 times or 1 time in memory?


A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is ok inside of the function, but writing inside of this function will generate a compiler error.

It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)

As usual when dealing with the const keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const only apply when adding const to the end of the function declaration after the parenthesis. const is a highly overused qualifier in C++ and the syntax and ordering is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:

Const correctness

The C++ 'const' Declaration: Why & How