11.5 CONST MEMBER FUNCTIONS IN C


11.5 CONST MEMBER FUNCTIONS IN C++

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;     } 




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net