Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 756
Edoz Avatar asked Apr 29 '11 04:04

Edoz


People also ask

What does adding const at the end of a function mean?

In essence it means that the method Bar will not modify non mutable member variables of Foo .

What does adding const to a member function do?

const member functions Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.

Is it a good practice to use const?

const is a one-off assignment variable. Reasoning about a const variable is easier (compared to let ) because you know that a const variable isn't going to be changed. A good practice when choosing the declaration type of variables is to prefer const , otherwise use let .

Why do we use const at the end of a function header?

Putting const after a function declaration makes the function constant, meaning it cannot alter anything in the object that contains the function.


1 Answers

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.

like image 168
Neil G Avatar answered Sep 28 '22 06:09

Neil G