简体   繁体   中英

Do I always have to declare any method that doesn't affect instance state, as const?

I have a class with the following method:

int getLength() {
    return length;
}

(The class is called String , I'm defining it for practice).

When I tried to compile, I got an error regarding a line of code that calls this method:

passing 'const String' as 'this' argument of int String::getLength() discards qualifiers.

A search on this site made me realize I needed to add const in the method declaration. It fixed the problem.

My question:

Do I always have to declare any method that doesn't affect instance state, as const ? And if I don't, I get a compile time error? Seems very odd.

If I don't have to do this always, than what are the situation when I do have to declare the method as const ?

The compiler error is not caused by the method, but by the type of the instance you are calling it on. You try to call a non-const method on a const object ( const String ) or reference to const object ( const String& ). This is rightfully rejected by the compiler.

And, yes, you should mark all methods which are logically const as const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM