kohansey wrote:by declaring a function const, basically means that the function can be called within another const function
By having a function return a const value, it is an "almost" guarantee that the object returned will not get changed outside the class for which it originated. I say almost, because you could always do a const_cast and cast away the const.
Read Effective C++: 50 Specific Ways to Improve Your Programs and Design
Well you were right on the second part, but not the first part.
The
const keyword after a function means that the if the user were to create an instance of that class, they would still be able to use that method. Basically
const means that that method isn't modifying any data in the class. But there is a catch to this! Suppose you want to have a
const method that modifies only a specific piece of data. Well then you declare that data
mutable, and it will be able to be manipulated by any function whether the class instance is constant or not.
Examples:
Code: Select all
class A
{
int num;
mutable int modify_me;
int getNum() { return num; }
void setModifyMe(int newInt) const { modify_me = newInt; }
};
This is a big no-no
in this case. If getNum() was
const, then this code would work perfectly fine.
This words, because modify_me is
mutable.
So basically
const makes sure that the data within the class is read-only. (With exceptions explained above.)