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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.