Thursday, May 22, 2014

const after a function declaration (C++) [Note]

const after a function declaration means that the function is not allowed to change any class members (except ones that are marked mutable). So this use of const only makes sense, and is hence only allowed, for member functions. Declaring a member method results in a function declaration that takes a member pointer as a first parameter. So a method 

int Foo::Bar(int random_arg) 

(without the const at the end) results in a function like this 

int Foo_Bar(Foo* this, int random_arg)

, and a call like

 Foo f; f.Bar(4);

will result in something like 

Foo 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)

Source:

http://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration
(Janick Bernet's Answer)

No comments:

Post a Comment