I got a book, where there is written something like:
class Foo
{
public:
int Bar(int random_arg) const
{
// code
}
};
What does it mean?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A "const function", denoted with the keyword
constafter a function declaration, makes it a compiler error for this class function to change a data member of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit
thispointer. So a methodint Foo::Bar(int random_arg)(without the const at the end) results in a function likeint Foo_Bar(Foo* this, int random_arg), and a call such asFoo f; f.Bar(4)will internally correspond to something likeFoo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer:int Foo_Bar(const Foo* this, int random_arg). Since the type ofthisin such case is const, no modifications of data members are possible.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
constkeyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage ofconstonly applies when addingconstto the end of the function declaration after the parenthesis.constis a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings aboutconstcorrectness and theconstkeyword:Const correctness
The C++ ‘const’ Declaration: Why & How