Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Mutators

A mutator  is a member function that can modify an object. Every non-const member function of a class is a mutator. In the simplest case, a mutator just assigns a new value to one of the member variables. In general, a mutator performs some computation and modifies any number of member variables.

Program gif defines three mutators for the Complex class. The first two, SetReal and SetImag, simply assign new values to the real and imag member variables, respectively.

   program57372
Program: Complex Class Mutators

Program gif also shows how the assignment operator, operator=, can be overloaded  . By overloading the assignment operator in this way the function is called whenever a complex number is assigned to another like this:

c = d;

If the programmer does not define an assignment operator explicitly, the C++ compiler generates one. The compiler-generated assignment operator simply assigns one-by-one the member variables of the class by invoking their respective assignment operators.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.