Code Example: Static vs. Dynamic Binding

Static Binding

The code segment below checks the type of the current Vehicle and calls the corresponding function:

switch (myVehicle->type) {

case CAR:

x = stopCar();

break;

case PLANE:

x = stopPlane();

break;

case BIKE:

x = stopBike();

break;

default:

error("Invalid");

}

This is difficult and error-prone to maintain, when new types of vehicles are added...

Dynamic Binding

The switch-statement above can be replaced by sending a message to the object which the variable myVehicle currently refers to:

x = myVehicle->stop();
In C++, the variable myVehicle would have been declared to be of type "reference to an instance of class Vehicle, or one of its subclasses":

Vehicle* myVehicle;

previous | next | start | contents | dictionary | help | evaluation

© Ericsson Telecom AB, 1995, Stockholm, Sweden