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

Classes : a concrete example

Classes extend structs by coupling methods directly to the data. This allows us to model real-world objects. Consider the problem of modeling a car (for, say, a traffic simulation). In English, you might say:

A car is an object that has a position, a speed, a certain amount of gas, and a certain number of passengers. When you accelerate, the amount of gas goes down and the speed increases according to its mileage. When you brake, the speed decreases. When you park, the speed goes to zero.

Classes allows us to express this design almost directly in code:

struct Point { Point(); Point(int x, int y); int x, y; }; class Car { public: Car(int initX, int initY); // Constructor void accelerate(double factor); void brake(double factor); void park(); Point getPosition() const; // Example of selector void setPosition(Point pos); // Example of mutator private: Point position; double speed, gas; int passengers; };

Note: the above is a class type definition. It defines data members for the class, and it declares member functions on that class. This class definition would typically go in the corresponding header file for this class---for example, car.h


Last modified: Mon Jun 26 22:18:50 PDT 2000