Q&A

Q1:If using a const function to change the class causes a compiler error, why shouldn't I just leave out the word const and be sure to avoid errors?
A1: If your member function logically shouldn't change the class, using the keyword const is a good way to enlist the compiler in helping you find silly mistakes. For example, GetAge() might have no reason to change the Cat class, but if your implementation has this line
if (itsAge = 100) std::cout << "Hey! You're 100 years old\n";

declaring GetAge() to be const causes this code to be flagged as an error. You meant to check whether itsAge is equal to 100, but instead you inadvertently assigned 100 to itsAge. Because this assignment changes the class, and you said this method would not change ...

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.