Why use const after the function?

5

I noticed in some code from other C ++ programmers that use functions like:

bool CClass::isRunning() const
{
    return this->_running;
}

I understand that in this way it is not possible to modify any member of the class, only serves for value return. So why use them? Is there any benefit in this? Would not it be easier and more economical to call the variable directly than to create a function for it?

    
asked by anonymous 16.01.2017 / 20:11

1 answer

5

Actually, it is not used after a function, but after a method. After all, what it does is make the pointer to this , that is, for the current instance, a constant. So you can not change any member of this object. It is a way of ensuring that the method does not produce side effects on the object.

In fact members that are declared as mutable can be changed anyway, so it is not well guaranteed.

As far as possible, it is useful to do all methods const . This facilitates some optimizations and gives a good indication to prevent someone from improperly changing the algorithm and tinkering with the object's state. If a programmer chooses to create state change in the code it will have to take the const to compile. And this is a change in the API of the class.

Let's suppose that this class has a method like this:

void CClass::Run() {
    this->_running = true;
}

You can not use const because the method is changing the state of the object.

In fact it might be better to call the variable directly, if you have full control over the code. Are you sure that in the future access to this variable will not only get its value and will have an algorithm that manipulates it? This is done pre-emptively so you do not have to change all the codes that will consume your class. Made with the method you create an indirection, which makes access more flexible.

This is especially true when there is dynamic linking where you do not even know how the code will be called and an indirection is needed.

    
16.01.2017 / 20:49