const Member Functions

If you declare a class member function to be const, you are promising that the method won't change the value of any of the members of the class. To declare a class method as constant, put the keyword const after the parentheses, but before the semicolon. The declaration of the constant member function SomeFunction() takes no arguments and returns void. It looks like this:

void SomeFunction() const;

Get accessor functions (some programmers call them “getter functions”) are often declared as constant functions by using the const modifier. The Cat class has two accessor functions:

 void SetAge(int anAge); int GetAge();  ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.