C++ const in getter

nkint picture nkint · Jan 31, 2014 · Viewed 39.3k times · Source

I'm still learning about C++ and I'm reading everywhere that I have to use const everywhere I can (for speed reason I think).

I'm usually write my getter method like this:

const bool isReady() {
    return ready;
}

But I've seen that some IDE autogenerate getter in this way:

bool getReady() const {
    return ready;
}

But, writing delegates, it happened to me to find this error if the const is after the function:

member function 'isReady' not viable: 'this' argument has type 'const VideoReader', but function is not marked const

So that, what is the better way to write a const getter? Do I really have to care about?

Answer

mkaes picture mkaes · Jan 31, 2014

There is a huge difference between the two ways.

const bool isReady()

The code above will return a const bool, but it does not guarantee that the object will not change its logic state.

bool isReady() const

This will return a bool, and it guarantees that the logic state of your object will not change. In this case it is not necessary to write const in front of the return type. It makes no sense to return a const bool because it is a copy anyway. So making it const is useless. The second const is needed for const correctness, which is not used for speed reasons but to make your program more reliable and safe.