Main Content

Extended and Associated objects - what is the difference - C++ example

Archive - Originally posted on "The Horse's Mouth" - 2013-01-18 11:58:02 - Graham Ellis

When you use inheritance, you create a tree of object types, where one type is based on another. For example, you define a base class of "transport" and then you extend that to define similar classes with extras called "bus" and "train". That's a very different matter to using a class connected in another way - for example if we wanted to have a class for all the various pieces of transport used on between two towns. For that, we'll use an associated class, which is simply a class that's used in conjunction with (and perhaps depends on) the other classes.

Here's some code where I've set up an object of type "flow" to contain a whole collection of objects of type "train" or "bus". Trains and buses are "transports" - so that's inheritance in use, but flow is just an associated class:
  Flow *chippenham_trowbridge = new Flow(6);
  chippenham_trowbridge->add(new Train(2,73));
  chippenham_trowbridge->add(new Train(1,69));
  chippenham_trowbridge->add(new Bus(2,61));
  chippenham_trowbridge->add(new Bus(1,81));


I've then made use of the flow object:
  int seatsonflow = chippenham_trowbridge->getseats();
  int vehiclesonflow = chippenham_trowbridge->getunits();
  int driversonflow = chippenham_trowbridge->getdrivers();
  
  cout << "Seats on flow: " << seatsonflow << endl;
  cout << "Vehicles on flow: " << vehiclesonflow << endl;
  cout << "Drivers on flow: " << driversonflow << endl;


The code to add a Transport item onto the Flow collection is like this:

  void Flow::add(Transport * item) {
    route[nroutes++] = item;
    }


And here is one of the methods on the Flow object which calls methods on its associative objects:

  int Flow::getunits() {
    int so_far = 0;
    for (int k=0; k<nroutes; k++) {
      so_far += route[k]->getveh();
      }
    return so_far;
    }


Complete example from today's C++ course: [here].