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 easier to use and easier to maintain.



Problem



JG Question



1. What makes interfaces “easy to use correctly, hard to use incorrectly”? Explain.

Guru Question



2. 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 r, double i = 0 )

: real(r), imag(i)

{ }



void operator+ ( complex other ) {

real = real + other.real;

imag = imag + other.imag;

}



void operator<<( ostream os ) {

os << "(" << real << "," << imag << ")";

}



complex operator++() {

++real;

return *this;

}



complex operator++( int ) {

auto temp = *this;

++real;

return temp;

}



// ... more functions that complement the above ...



private:

double real, imag;

};

Note: This is not intended to be a complete class. For example, if you provide operator++ you would normally also provide operator–. Rather, this is an instructive example to focus on the mechanics of writing correctly the kinds of functions this class is trying to support.