[ Introduction to OOP ] [ Encapsulation ] [ Objects ] [ More on Objects ] [ Abstract Data Types ] [ Inheritance ] [ Abstract Classes ] [ Templates ]
  6. Inheritance
6.1 What is inheritance?

To inherit is to derive traits from preceding generations. In the object-oriented programming world, the term is associated with a kind of software reuse. With inheritance, new classes can be derived from existing classes, using the existing classes as building blocks. The new class inherits properties and methods from the base class. The new class can also add its own properties and methods.

Inheritance can be understood from the following skeleton example. In this case a parent or a base class called BankAccount is declared as follows:
 
class BankAccount{
protected:
   char* Name;
   char* SSNum;
   char* AccountNum;
   float Balance;
public:
   BankAccount  (char* name, char* ssnum);
   void Deposit (float amount, char* accnum);
   void Withdraw(float amount, char* accnum);
   void PrintBalance(char* accnum);
}

The base class BankAccount has four variables:

The methods Deposit and Withdraw are used to make a deposit and withdrawal from the bank account. The PrintBalance method prints the balance in the account. The BankAccount class in itself is not sufficient to carry out all the transactions on the account. Generally, there are two types of accounts: the checking account, which facilitates day to day transactions, and the savings account, which accrues interest on the saved amount.

We therefore derive two subclasses that inherit from the above parent class. They are SavingsAccount and Checking Account.
 
class SavingsAccount: public BankAccount{
private:
   float InterestRate;
   float MinimumBalance;
}

class CheckingAccount: public BankAccount{
private:
   float MonthlyFee;
}
 

The subclasses SavingsAccount and CheckingAccount inherit the properties of BankAccount.

The above example throws some light on the usage of the keywords public, private and protected. They are used in the following contexts:

6.2 University Student Example

The following presents a more detailed example of Inheritance.
 
// The class named UnivStudent prints a student's name and social security number.
// Two derived classes, GradStudent and UndergradStudent, are defined.

#include <iostream.h>

// The base class.
class UnivStudent{ private:
   char* FirstName;
   char* LastName;
   char* StudentId;
public:
   UnivStudent(char*, char*, char*);
   void StudentInfo();
};

UnivStudent::UnivStudent(char* fname, char* lname , char* idnum ){
   FirstName = fname;
   LastName  = lname;
   StudentId = idnum;
}
void UnivStudent::StudentInfo(){
   cout << " Student Name: " << FirstName << " " << LastName  << endl;
   cout << " Student Id:   " << StudentId << endl;
}

// The derived class GradStudent.
class GradStudent: public UnivStudent{
public:
   GradStudent(char*, char*, char*, int, int, int, int);
   int TotalCreditHours();
   void RegistrationInfo();
private:
   int ThreeHourCourses;
   int FourHourCourses;
   int ThesisHours;
   int SeminarHours;
};

// The constructor for GradStudent invokes the constructor of the
// base class UnivStudent and thus assigns values to the variables
// inherited from the base class.
GradStudent::GradStudent(char* fname, char* lname, char* idnum,
                         int n1, int n2, int n3, int n4)
            :UnivStudent(fname, lname, idnum){
   ThreeHourCourses  = n1;
   FourHourCourses   = n2;
   ThesisHours       = n3;
   SeminarHours      = n4;
}
int GradStudent::TotalCreditHours(){
   int TotalHours;
   TotalHours = ThreeHourCourses*3 + FourHourCourses*4 + ThesisHours + SeminarHours;
   return TotalHours;
}
void GradStudent::RegistrationInfo(){
   int CourseHours;
   CourseHours = ThreeHourCourses*3 + FourHourCourses*4;
   cout << " Graduate student registration details:" << endl;
   cout <<   UnivStudent::StudentInfo();
   cout << " Course Credit Hours:  " << CourseHours << endl;
   cout << " Thesis Credit Hours:  " << ThesisHours << endl;
   cout << " Seminar Credit Hours: " << SeminarHours << endl;
   cout << " Total credit hours registered:" << TotalCreditHours() << endl;
   cout << endl;
}

// The derived class UnderGradStudent.
class UnderGradStudent: public UnivStudent{
public:
   UnderGradStudent(char*, char*, char*, int, int, int);
   int TotalCreditHours();
   void RegistrationInfo();
private:
   int ThreeHourCourses,FourHourCourses;
   int ProjectHours;
};

UnderGradStudent::UnderGradStudent(char* fname, char* lname,
   char* idnum, int n1, int n2, int n3):UnivStudent(fname, lname, idnum){
   ThreeHourCourses  = n1;
   FourHourCourses   = n2;
   ProjectHours      = n3;
}
int UnderGradStudent::TotalCreditHours(){
   int TotalHours;
   TotalHours = ThreeHourCourses*3 + FourHourCourses*4 + ProjectHours;
   return TotalHours;
}
void UnderGradStudent::RegistrationInfo(){
   int CourseHours;
   CourseHours = ThreeHourCourses*3 + FourHourCourses*4;
   cout << " Undergraduate student registration details: " << endl;
   cout <<   UnivStudent::StudentInfo();
   cout << " Course Credit Hours:  "         << CourseHours        << endl;
   cout << " Project Credit Hours: "         << ProjectHours       << endl;
   cout << " Total credit hours registered:" << TotalCreditHours() << endl;
      cout << endl;
}

The main program that uses the above classes is as follows

int main(){
   GradStudent g1("Robert", "Johnson", "99990000", 2, 3, 4, 1),
               g2("Jane",   "Kopko",   "99990001", 3, 3, 2, 1);
   UnderGradStudent u1("Kenneth", "Lara", "99970000", 5, 3, 0),
                    u2("Sandy",   "Burke","99970001", 4, 4, 2);
   g1.RegistrationInfo();  g2.RegistrationInfo();
   u1.RegistrationInfo();  u2.RegistrationInfo();
   return 0;
}

The output is as follows:

Graduate student registration details
 Student Name: Robert Johnson
 Student Id:   99990000
 Course Credit Hours:  18
 Thesis Credit Hours:  4
 Seminar Credit Hours: 1
 Total credit hours registered:23

Graduate student registration details
 Student Name: Jane Kopko
 Student Id:   99990001
 Course Credit Hours:  21
 Thesis Credit Hours:  2
 Seminar Credit Hours: 1
 Total credit hours registered:24

Undergraduate student registration details:
 Student Name: Kenneth Lara
 Student Id:   99970000
 Course Credit Hours:  27
 Project Credit Hours: 0
 Total credit hours registered:27

Undergraduate student registration details:
 Student Name: Sandy Burke
 Student Id:   99970001
 Course Credit Hours:  28
 Project Credit Hours: 2
 Total credit hours registered:30
 

6.3 Vehicle example

Here is another example of inheritance. The use of protected members prevents access by classes other than explicitly derived classes. This example also demonstrates the hierarchical derivation of classes. The classes Bus and Car are derived from the Vehicle class, each adding some features to the base class. The class SchoolBus, in turn, is derived from the class Bus.
 
#include <iostream.h>
#include <string.h>
#include <conio.h>

// This is the base class. It defines the name of the manufacturer
// and the vehicle identification number.
class Vehicle{ protected:
   char* Manufacturer;
   char* VehicleId;
public:
  Vehicle(char* name, char* num);
  void display(void);
};

Vehicle::Vehicle(char* name, char* num)
        :Manufacturer(name), VehicleId(num);{ }
void Vehicle::display(void) {
   cout << endl;
   cout<< "Manufacturer:    " << Manufacturer << endl;
   cout << "Number:          " << VehicleId    << endl;
}

class Car: public Vehicle {
   int NumOfDoors, MaxSpeed;
public:
   Car(char* name, char* num, int doors, int maxspeed);
   void display();
};
Car::Car(char* name, char* num, int doors, int maxspeed)
    :Vehicle(name, num) {
   NumOfDoors = doors;
   MaxSpeed   = maxspeed;
}
// The display function does not override the display function of
// the base class. It simply uses the display function of the base 
// class and adds features relevant to the current class.
void Car::display(){
   Vehicle::display();
   cout << "Number of Doors: " << NumOfDoors << endl;
   cout << "Maximum Speed:   " << MaxSpeed   << endl;
}
class Bus: public Vehicle{
protected:
   int NumOfSeats;
   int NumOfWheels;
public:
   Bus(char* name, char* num, int seats, int wheels);
   void display();
};
Bus::Bus(char* name, char* num, int seats, int wheels)
    :Vehicle(name,num) {
   NumOfSeats  = seats;
   NumOfWheels = wheels;
}
void Bus::display(){
   Vehicle::display();
   cout << "Number of Seats:  " << NumOfSeats  << endl;
   cout << "Number of Wheels: " << NumOfWheels << endl;
}
 

We now go further down the inheritance tree by deriving a class from the derived class Bus. The class SchoolBus will inherit properties of the bus class as well as the vehicle class.
 
class SchoolBus: public Bus { protected:
   char* SchoolName;
public:
   SchoolBus(char* name, char* num, int seats, int wheels,
             char* school);
   void display();
};

SchoolBus::SchoolBus(char* name, char* num, int seats, int wheels, char* school)
          :Bus(name,num,seats,wheels), SchoolName(school) { }
void SchoolBus::display(){
   Bus::display();
   cout << "School Name:     " << SchoolName << endl;
}

The main program is as follows.

int main(void){
   Vehicle a1 ("Ford", "A123BCD");
   Car     c1 ("BMW",    "X123WYZ", 4, 240),
           c2 ("TOYOTA", "P123QRS", 2, 200);
   Bus     b1 ("TOYOTA", "A123XYZ", 15, 6),
           b2 ("Ford",   "BYTRE23", 50, 8);
   SchoolBus sb1("ABC","Q999IJK", 40, 6, "UT");

   cout << "Vehicle Information: ";    a1.display();
   cout << "Car Information: ";        c1.display();
   cout << "Bus Information: ";        b1.display();
   cout << "School bus Information: "; sb1.display();
   cout << endl;
   return 0;
}

The output of the above program is as follows:

Vehicle Information:
Manufacturer:    Ford
Number:          ABCD

Car Information:
Manufacturer:    BMW
Number:          X123WYZ
Number of Doors: 4
Maximum Speed:   240

Bus Information:
Manufacturer:    TOYOTA
Number:          A123XYZ
Number of Seats: 15
Number of Wheels: 6

School bus Information:
Manufacturer:    ABC
Number:          Q999IJK
Number of Seats: 40
Number of Wheels: 6
School Name:     UT
 

In short, inheritance aims at organizing objects and permitting the reuse of existing code. This is an important feature of object oriented programming languages.


 
[ Introduction to OOP ] [ Encapsulation ] [ Objects ] [ More on Objects ] [ Abstract Data Types ] [ Inheritance ] [ Abstract Classes ] [ Templates ]