Chapter 43. Const-Correctness
Difficulty: 6
const
is a powerful tool for writing safer code. Use const
as much as possible, but no more. Here are some obvious and not-so-obvious places where const
should—or shouldn't—be used.
Don't comment on or change the structure of this program; it's contrived and condensed for illustration only. Just add or remove const
(including minor variants and related keywords) wherever appropriate.
Bonus question: In what places are the program's results undefined/uncompilable due to const
errors?
class Polygon { public: Polygon() : area_(-1) {} void AddPoint( const Point pt ) { InvalidateArea(); points_.push_back(pt); } Point GetPoint( const int i ) { return points_[i]; } int GetNumPoints() { return points_.size(); } ...
Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions 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.