const keyword after a function
Why would you put the const keyword after a function such as
void SomeFunction() const
{
}
I know it makes it some the invoking object can't be changed, but why would you
do that. If your not going to change the object then who cares. If you are then
who cares. Does it do anything but take up space?
Two reasons:
1. As a promise to yourself. If you really don't intend to change the object, but do accidentally, the compiler will tell you about it.
2. As a promise to functions that call it. If you have a const pointer, you can only call const member functions on it.
An extremely useful page on const-correctness is here.
1. As a promise to yourself. If you really don't intend to change the object, but do accidentally, the compiler will tell you about it.
2. As a promise to functions that call it. If you have a const pointer, you can only call const member functions on it.
An extremely useful page on const-correctness is here.
Even if you don't care now, someone else who uses your code may care later (and that could be you). For some reason you may have to declare an object const, like if it's used as a key in an STL map. And adding the proper consts after the fact is something of a pain.
Quote:Original post by SiCrane
Even if you don't care now, someone else who uses your code may care later (and that could be you). For some reason you may have to declare an object const, like if it's used as a key in an STL map. And adding the proper consts after the fact is something of a pain.
[grin] yeah...for example I'm someone who cares about const. I want const everywhere!
to cptrnet
Really! When I see a function I want to know what is the data in (const) and the data out (not const); I want know if the object will be modified or not and why.
If you dont follow these (simple) rules your code will be usefull only to you. Sure.
I haven't done a whole lot of coding yet so I think I can add const keyword without it ruining my code, but how do I know where to put it, should I put it after everything that doesn't change the invoking object for good measure?
Put it after functions that logically don't change the state of your class. Like a function that returns the name or length of an object. Then if you trigger a compiler error in that function then you know you're probably implementing the function wrong.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement