Also, in the second use (putting
const after the function signature and before the function body), when used in a member function of a class, makes the function promise not to alter the object of the class, and this function can be called from a constant instance. Like this:
Code:
class cApplesauce
{
private:
int m_iTheValue;
public:
void setTheValue (int iNewValue)
{
m_iTheValue = iNewValue;
}
int getTheValue () const
{
return m_iTheValue;
}
}
This example class just has set/get functions for m_iTheValue. Notice
const after the getTheValue function.
Code:
cApplesauce theObject;
theObject.setTheValue (42);
cout << theObject.getTheValue () << endl;
const cApplesauce theConstObject = theObject;
theConstObject.setTheValue (69); // Not allowed!
cout << theConstObject.getTheValue () << endl;
This code snippet instantiates a regular object, sets its value, and prints it. It is okay to set the value.
Then it instantiates a
const object (by copying the regular object (which will set its value to 42)), and attempts to set its value to 69. That won't work; the set function has not promised to change the value, and this is a const object. Then it prints the value, which works because the get function HAS promised not to change anything.
Thanks,
Mark