Accessors are defined to be "const" functions. This means that the compiler stops them from changing the private data in the object. They usually return data and so are usually not void.
Mutators must not be "const" and should be "void" functions.
Both mutators and accessors can have parameters if needed.
You may meet functions that don't have the const but do not change the data in the class. THese arenether accessors or mutators. These are a source of sneaky bugs and should be avoided and if possible refactored.
A getter is a special kind of accessor that "gets" the value of a private variable. Its name should start "get". These are very common.
double getSize()const{return size;}
A setter is a special kind of mutator that "sets" the value of a private variable. Its name should start "set". These are quite common.
void setSize(double s)const{size = s;}
type class::name( arguments ) { body }
For example
void Snake::slither( double meters ) { .... }
Sound Snake::sound( )const { return "hiss" }
void Snake::swallow( Animal prey ) { .... }
Member functions are either constructors, mutators, or accessors.
Here is a sample: [ test.circle.cpp ]
class Circle
{
private:
double radius;
public:
Circle() {radius=0;}
Circle(double r) {radius=r;}
double getRadius()const { return radius; }
void setRadius(double v) { radius=v; }
double getCircumference()const{ return PI*radius; }
}; //don't loose the semicolon.
Inline member functions are very useful for getters, setters, and constructors.
I use this in quizzes and class work because I need to get the whole thing into a single slide or page.
Class object;Answer: The Class::Class constructor is called to make sure that 'object' is ready for use.
The default constructor constructs default objects!
Example code [ product2.cpp ]
Class object(parameters);
className::className(parameters)
{
code
}
object = Class();
object = Class(parameters);Notice that the new value of the object overwrites the values in the old object.
But follow the Golden Rule: Write code as if you are going to be reading and changing it.
You must tackle one of the programming projects at the end of Chapter 5 -- create a class and test it.
Members of a class: [ 12ex.cpp ]
Here is a Microwave class ... [ 13ex2.cpp ] What can you add to it?