next up previous contents index
Next: Java Up: C++ Previous: Constructors   Contents   Index


Inheritance

As with Perl, C++ supports the idea of it inheritance - a child class can inherit attributes and methods from a parent. As an example, let us consider a vehicle class:
// file vehicle.h
class vehicle {
public:
  bool family;
  void print_info(void);
};
with code appearing in
// file vehicle.cpp
#include <iostream.h>
#include "vehicle.h"
void vehicle::print_info(void) {
  if (family == true) {
    cout << "This is a family vehicle." << endl;
  }
  else {
    cout << "This is not a family vehicle." << endl;
  }
}
which has a single attribute - a boolean family, indicating if it's a family vehicle, and a method print_info, to print out the vehicle information. This can be used as
#include <iostream.h>
#include "vehicle.h"

int main(void) {
  vehicle bmw;
  bmw.family = false;
  bmw.print_info();
  return 0;
}
Now let us define a child class bus, inheriting from the vehicle and having an additional attribute, capacity, indicating the number of passengers that may be carried. We will also add an additional method, set_capacity, to set this attribute, and also modify the print_info method of the vehicle to include printing out the addtional information.

The child's class definition appears in the header file

// file bus.h
#include "vehicle.h"
class bus : public vehicle {
public:
  int capacity;
  void set_capacity(int);
  void print_info(void);
};
where the inheritance is specified through the class : public parent notation. Note that we only have to specify what attributes and/or methods we want added or overridden - if not specified, those of the parent will be used. The code for the methods appears in
// file bus.cpp
#include <iostream.h>
#include "bus.h"

void bus::set_capacity(int input) {
  capacity = input;
}
void bus::print_info(void) {
  vehicle::print_info();
  cout << "The capacity is " << capacity << endl;
}
Note the use of vehicle::print_info to access the parent print_info method. An example of the use of this class is
// file greyhound.cpp
#include <iostream.h>
#include "bus.h"

int main(void) {
  bus greyhound;
  greyhound.family = false;
  greyhound.set_capacity(55);
  greyhound.print_info();
  return 0;
}
The sequence for which to compile it is
  cc -c vehicle.cpp
  cc -c bus.cpp
  cc -o greyhound greyhound.cpp vehicle.o bus.o


next up previous contents index
Next: Java Up: C++ Previous: Constructors   Contents   Index