|
If the sole purpose of a member function in C++ is to retrieve data that may be in the private section of an object, it is best to declare such a function to be of type const, as in the example below:
class Date { int d, m, y; public: int getDay() const { return d; } int getMonth() const { return m; } int getYear() const; // .... };
By declaring the ‘get’ functions to be const, the compiler will make sure that the code written for these functions does not inadvertently alter the state of the object.
The tag const is also required in the headers of such member functions if they are defined outside the class. For example, the header of the getYear() function declared above must contain const as shown below:
int Date:: getYear() const { return y; }
|