[   ^ to index...   |   <-- previous   |   next -->   ]

Classes : implementing member functions

On the previous page, we defined the interface for this class. In car.cpp, we would define the following implementation:

#include "car.h" const int MILEAGE_PER_UNIT = 0.02; const double INIT_GAS = 10.0; Car::Car(int initX, int initY) { position.x = initX; position.y = initY; speed = 0; gas = INIT_GAS; } void Car::accelerate(double factor) { speed += factor; gas -= MILEAGE_PER_UNIT * factor; } void Car::brake(double factor) { speed -= factor; } void Car::park(double factor) { speed = 0; } Point Car::getPosition() { return position; } void Car::setPosition(Point pos) { position = pos; }

Notice that the member variables (also called fields) of the Car class are automatically visible to member functions (also called methods) of the class.

Having defined the above, we would then be able to write (in any linked file):

Car myCar; myCar.accelerate(1.0); myCar.park(); Point currentPos = myCar.getPosition();

Last modified: Wed Jun 28 15:42:08 PDT 2000