const - a client-server contract
// the constructors for body
// the member functions we already know
virtual float GetVolume() =0;
virtual float GetSurface() =0;
// two more functions which deal with the color
virtual void setColor (Color *c);
virtual Color * getColor();
We have seen the definition
we do not want really want to change c, or do we? No.
If we now attempt to modify the object which c points to anyway, we get a compiler error.
GetVolume and getSurface just return values, they do not actually change the object’s properties. We inform the compiler:
virtual float GetVolume() const = 0;
tells the compiler that as a result of this call, the object is supposed to remain unchanged.
The server guarantees that it won’t modify an object that we let it use, and we really can rely on the contract.
The const function definition will catch all attempts to “illegally” modify the object, and eases the bookkeeping work in a distributed environment.
Note: float GetVolume()const and float GetVolume()are considered two different functions!
This is called a client-server contract.