The purpose of const on member functions is to identify which member functions may be invoked on const objects. They make the interface of a class easier to understand. It is important to know which funtions may modify an object and which may not. They make it possible to work with const objects. That is a critical aspect of writing efficient code because one of the fundamental ways to improve a program's performance is to pass objects by reference-to-const. This is only viable if there are const member function with which to manipulate the resulting const-qualified objects.
If in that example there was a function:
1 2 3 4
float pay(float hoursWorked);
//The signature for these two methods are different, they are 2 separate functions.
float pay(float hoursWorked) const;
The non const function could change the objects state (so could the const one with const casting but that is another can of worms)
Lets say you had a function that does something with an employee object.
It usually denotes that the function is read-only.
This means that it won't modify anything.
In your example, the first two functions are access functions, so it makes sense for them to be const. Not sure about the pay() function, though. Hard to tell without the declaration, really.
Not sure about the pay() function, though. Hard to tell without the declaration, really.
ico
The pay function, while making modifications to something, still maintains the logical constness of the object. It looks like it takes in hoursWorked, probably uses the payRate and calculates the actual "paid" amount and returns it. Making no changes to the object, thus maintaining it's contract as const.
Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called.
// constant_member_function.cpp
class Date
{
public:
Date( int mn, int dy, int yr );
int getMonth() const; // A read-only function
void setMonth( int mn ); // A write function; can't be const
private:
int month;
};
int Date::getMonth() const
{
return month; // Doesn't modify anything
}
void Date::setMonth( int mn )
{
month = mn; // Modifies data member
}
int main()
{
Date MyDate( 7, 4, 1998 );
const Date BirthDate( 1, 18, 1953 );
MyDate.setMonth( 4 ); // Okay
BirthDate.getMonth(); // Okay
BirthDate.setMonth( 4 ); // C2662 Error
}