is it good practice to add const at end of member functions - where appropriate?

Edoz picture Edoz · Apr 29, 2011 · Viewed 7.3k times · Source

Is it a good practice, in C++, to add const at the end of a member function definition every time the function does not modify the object, i.e., every time the function is 'eligible' for const? I know that it's necessary in this case:

class MyClass {

public:
int getData() const;
};

void function(const MyClass &m) { int a = m.getData(); dosomething... }

but other than this, and other uses of const for actual functionality, does adding const to the end actually change the way code is executed (faster/slower) or is it just a 'flag' for the compiler to handle cases such as the one above? In other words, if const (at the end) is not needed for functionality in a class, does adding it make any difference?

Answer

Neil G picture Neil G · Apr 29, 2011

Please see this excellent article about const correctness by Herb Sutter (C++ standards committee secretary for 10 years.)

Regarding optimizations, he later wrote this article where he states that "const is mainly for humans, rather than for compilers and optimizers." Optimizations are impossible because "too many things could go wrong...[your function] might perform const_casts."

However, const correctness is a good idea for two reasons: It is a cheap (in terms of your time) assertion that can find bugs; and, it signals the intention that a function should theoretically not modify the object's external state, which makes code easier to understand.