Home Segments Index Top Previous Next

449: Mainline

Importantly, however, if you define an array of pointers to objects in a certain class, the actual pointers can point not only to any object in that class, but also to any object in its subclasses.

The following, for example, defines train to be an array of pointers to objects in the railroad_car class:

// Define railroad car pointer array: 
railroad_car *train[100]; 

Once you have created such an array of pointers to objects in the railroad_car class, you can arrange for particular pointers to point to railroad_car objects that also happen to be in the engine, box_car, tank_car, or caboose classes.

The following, for example, arranges for the first pointer in the train array to point to a railroad_car object that also happens to be an engine object created at run time by the new operator:

// Allocate memory for an engine, and 
// cast engine* pointer into a railroad_car* pointer: 
train[0] = new engine;