Recommended Posts

bigdilliams    118
Hello forum,
here's my question:

What does the "const" at the end of a function do?

[CODE]
bool CheckAnimation(........) const;

const FrameSkeleton& GetSkeleton() const
{
return ........;
}
[/CODE]

Share on other sites
Brother Bob    10344
In C++, it applies to member functions and specifies that the function does not modify the object with which it is called. You can only call const-functions on a const object, and you cannot call non-const functions on a const object.

Share on other sites
bigdilliams    118
Thank you my question is answered

Share on other sites
alvaro    21263
[quote name='Brother Bob' timestamp='1353166388' post='5001769']
You can only call const-functions on a const object
[/quote]
That's not right. You probably meant to say something else...

Share on other sites
alvaro    21263
Member functions are essentially functions that take an implicit first parameter (called this'), which is a pointer to the object on which they are called. A const member function is one in which the this' pointer is const.

Share on other sites
Brother Bob    10344
[quote name='Álvaro' timestamp='1353170268' post='5001780']
[quote name='Brother Bob' timestamp='1353166388' post='5001769']
You can only call const-functions on a const object
[/quote]
That's not right. You probably meant to say something else...
[/quote]
No, I meant what I wrote, but I see now how my statement can be read in two ways that have different meanings. You can call anything on a non-const object, but only const-functions on a const object.

Share on other sites
alvaro    21263
Oh, I can now see the other interpretation. I had tried before and failed. Now the sentence is strange because it is the conjunction of two clauses that mean the same thing. That's probably why my brain kept refusing to see what you meant.

Share on other sites
SiCrane    11839
[quote name='Brother Bob' timestamp='1353171150' post='5001787']
You can call anything on a non-const object, but only const-functions on a const object.
[/quote]
Well to be pedantic, there are also volatile functions and objects (and const volatile functions and objects). If an object is non-const, but volatile, you can't call a const-function that isn't also a volatile function on it. And if you've got a const object you can also call a const and volatile function on it. Fortunately, volatile and const volatile functions are very rare in the wild.

Share on other sites
bigdilliams: the other guys already answered what it does, but I wanted to add when and why to use it. Basically, any time you know the function should not modify the object, make it const. Then when you accidentally try to modify one of those objects, the compiler will catch it and you get a clear error message instead of a painful debug session. The const labels will also help when reading the code and reasoning about it.