Fixing (some of) Body’s design flaws now...
// the constructors for body
// the member functions we already know
virtual char* identify() const =0;
virtual float GetVolume() const =0;
virtual float GetSurface() const =0;
// two more functions which deal with the color
virtual void setColor (const Color *c);
virtual Color * getColor() const;
Let’s make a client-server contract and add the const keywords where they belong:
body::body(const Color *c)
// we just grab the pointer to the color provided.
our_color = 0; // we did not make the color class.
body.C: In method `body::body(const Color *)':
body.C:16: warning: assignment to `Color *' from `const Color *' discards const
body.C: In method `void body::setColor(const class Color *)':
body.C:32: warning: assignment to `Color *' from `const Color *' discards const
But the compiler is not happy...
- We say that we will not modify the Color object which we get (and we don’t in either call)
- However, we retain a pointer to it and can at least potentially modify it
- Worse, we will hand out a pointer to the Color object to anybody who asks for it and has no obligation to honor the “const” contract.
The solution is to make a copy of the Color object which no one else gets to see.