Chapter 20. Class Mechanics

Difficulty: 7

How good are you at the details of writing classes? This item focuses not only on blatant errors, but even more so on professional style. Understanding these principles will help you to design classes that are more robust and easier to maintain.

You are doing a code review. A programmer has written the following class, which shows some poor style and has some real errors. How many can you find, and how would you fix them?

 class Complex { public: Complex( double real, double imaginary = 0 ) : _real(real), _imaginary(imaginary) { } void operator+ ( Complex other ) { _real = _real + other._real; _imaginary = _imaginary + other._imaginary; } void operator<<( ostream os ) { os << "(" << _real << "," << _imaginary ...

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.