Why use const after function?

Asked

Viewed 1,855 times

7

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

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

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

1 answer

7


It is not actually 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 cannot change any member of this object. It is a way to ensure that the method does not produce side effects on the object.

Actually members who are declared as mutable can be changed anyway, so it’s not quite guaranteed.

As far as possible it is useful to do all the methods const. This facilitates some optimizations and gives a good indication to prevent someone from altering the algorithm inappropriately and tampering with the state of the object. If a programmer decides to create a change of state in the code he will have to take the const to compile. And that’s a change in the class API. That’s a protection.

Suppose this class has a method like this:

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

I put in the Github for future reference.

Can’t 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 just take its value and have an algorithm that manipulates it? This is done preemptively so you don’t have to change all the codes that will consume your class. Done with the method you create a indirect, which makes access more flexible.

This is especially true when there is linkediting dynamics (DLL) where you don’t even know what the code will be called and an indirect is needed.

  • Oh yes. I get it! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.