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

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