2.2 CONSTRUCTORS
Constructors are a way to provide an initialization that is guaranteed to be called. A constructor is a member function with these special properties:
- The name of a constructor must be the same as the name of the class.
- A constructor does not have any return value. The compiler knows that every constructor has no return value. but a compiler error occurs if you actually write void at the front of the constructor's head.
- If a class has a constructor, then a constructor is called automatically whenever a variable of the class is declared.
Adding a constructor to the throttle class
Our throttle constructor has one parameter, which tells the total number of positions that the throttle contains. Here is the prototype for the new constructor, along with its precondition/postcondition contract:
throttle (int size)
// Precondition: 0 < size.
// Postcondition: The throttle has size positions above the shutoff position,
// and its current position is off
The constructor's prototype is placed in the throttle class definition along with the other member functions' prototypes, as indicated here:
class throttle
{
public:
// CONSTRUCTOR
throttle (int size);
// MODIFICATION MEMBER FUNCTION
void shut_off();
...
Let us see some examples of using the constructor in declarations of throttle objects.
throttle mower_control (4);
throttle apollo (4