The polar point class illustrates the use of a private method to maintain an invariant on the internal state of an object. The class enforces the assertion that the radius rho is positive and that the angle theta is between 0 and 360. This simplifies writing methods that manipulate points, for example consider writing the method quadrant() with and without this assertion. All methods that manipulate a point call normalize() before returning; this maintains the invariant. Unlike structs, the visibility rules for C++ guarantee no outside code can violate the assertion by modifying rho or theta.
class point
{
private:
SafeFloat rho, theta;
void normalize()
{
if (rho < 0.0)
{
theta += 180.0;
rho = -rho;
}
while (theta > 360.0)
theta -= 360.0;
while (theta < 0.0)
theta += 360.0;
}
public:
point(SafeFloat r, SafeFloat t) : rho(r), theta(t) {normalize();}
. . .
};