Small question about functions

Started by
7 comments, last by Stroppy Katamari 11 years, 4 months ago
Hello forum,
here's my question:

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


bool CheckAnimation(........) const;

const FrameSkeleton& GetSkeleton() const
{
return ........;
}
Advertisement
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.
Thank you my question is answered :D

You can only call const-functions on a const object

That's not right. You probably meant to say something else...
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.

[quote name='Brother Bob' timestamp='1353166388' post='5001769']
You can only call const-functions on a const object

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.
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.

You can call anything on a non-const object, but only const-functions on a const object.

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.
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.

This topic is closed to new replies.

Advertisement