C++ class inheritance











Introduction to C++ class inheritance


Inheritance is a technique in which a C++ class known as the derived class absorbs, utilizes and enhances the data and behavior of another class known the base class . Inheritance enhances object-oriented programming in a way that it saves program development time, and supports reuse of debugged high quality software. Inheritance allows an object oriented programmer to focus on the larger picture rather than specific cases. Because different classes sometimes require similar data members, inheritance enables avoidance of duplication of codes in the same project environment. The base class captures the most common members and then supplies them to the derived classes with the help of inheritance technique.


Consider the hospital community which includes patients, attendants, staff and directors. The patients can be outpatients or inpatients. The staff could be medical staff or administrative staff and the medical staff could also serve as attendants. The figure below shows the type of relationship each category or class would have with the other. Starting from the bottom it can be inferred that an outpatient or inpatient has a single inheritance in that it inherits only from the patients class. The medical staff class has a multiple inheritance (relationship) in that it inherits from the staff, administrator and attendant classes


Now let say that we try to develop for each person in the hospital community category a class to contain the following data members; Name, sex, age, status in the hospital and contacts. Our classes would obviously contain duplicated data members and the set and get member functions. Even then we would fall into trouble with the class HospitalCommunity, because any member in the other classes is a member of this class. That being the case, we can develop data and member functions within the HospitalCommunity class and let all other classes inherit from it through their respective hierarchy.

To enable the HospitalStaff class inherit from the HospitalCommunity class we write the definition as follows.
class HospitalStaff: public HospitalCommunity
  
  {..........
  ...........
  }

The key word public refers to public inheritance implying that the inherited members of the base class HospitalCommunity will become public members of the derived class HospitalStaff. But members of the base class HospitalCommunity are accessed in the form they were declared in that class. HospitalStaff class will access and modify public or protected members of the HospitalCommunity but cannot directly access and modify the private members. Private members are hidden in the derived class and can only be accessed through the public or protected member functions and friends of the base class.Public inheritance is referred to as is-a relationship because the objected of the derived class is also an object of the derived class, i.e an outpatient is a patient and a patient is a member of the hospital community.


We can also use the key words protected or private to allow the derived class have a protected in heritance or a private inheritance. A protected in heritance implies that public and protected members of the base class become protected members of the derived class. The derived class can access directly public and protected members of the base class but not the private members. Private members are hidden in the derived class and can only be accessed through the public or protected member functions and friends of the base class.


A private inheritance implies public and protected members of the base class become private members of the derived class. The derived class can access directly public and protected members of the base class but not the private members. Private members are hidden in the derived class and can only be accessed through the public or protected member functions and friends of the base class. Protected and private inheritance refers to a composition or the has-a relationship in that an object of the derived class has parts of different base classes. For example a moving car includes the driver, passengers and the cargo. The car is a vehicle and so it inherits from a vehicle class but also from the people and cargo classes.


In the example below we deal with one simple case of the HospitalStaff class inheriting from the HospitalCommunity class.

#include<iostream>
#include<string>
#using namespace std;

class HospitalCommunity
{

string fname;
string sex;
int age;
long conta;

public:
HospitalCommunity(string n, string s, int g, long ct)
{fname=n; sex=s; age=g; conta=ct;}

string getName()const {return fname;}
string getSex()const{return sex;}
int getAge()const {return age;}
long getCont()const{return conta;}
void printCom()const
{
//member functions are be used to allow for public inheritance 

cout<<getName()<<setw(8)<<getSex()<<setw(4)<<getAge()<<setw(12)<<getCont();} 
};


class HospitalStaff:public HospitalCommunity
{
public:
HospitalStaff(const string &fn, const string &sx, int ag, long cont, string pos)
:HospitalCommunity(fn,sx,ag,cont){position=pos;}
string getPos()const{return position;}

void printEmpl()const
{cout<<setw(7)<<"Name"<<setw(12)<<"Sex"<<setw(6)<<"Age"<<setw(10)<<"Contacts"<<setw(15)<<"Position"<<endl;
cout<<endl;
HospitalCommunity::printCom();   // call to base class member function printCom()
 
cout<<setw(20)<<getPos();}

private:
string position;
};


int main()
{
HospitalStaff newStaff("Aine Namanya","Female",21,0772567546,"Clinical Officer");
 newStaff.printEmpl(); 
return 0;
}
Output:
Name         Sex   Age  Contacts       Position

Aine Namanya  Female  21   132837222    Clinical Officer
In the above example class HospitalStaff does not redefine data members name, sex, age and contacts. It only inherits these from the base class HospitalCommunity. The constructor of the base class is called to initialize the inherited data members. The initialization takes place in the initialization list of the constructor of the derived class. The constructor and the destructor of the base class are not inherited. The derived class must explicitly call the constructor and the destructor where their services are needed.


Even though printCom()the member function of the base class is inherited, the derived class is able to modify it and print according to its preferences. Also, in addition to the inherited data members, the derived class HospitalStaff is able to create its specific own data member position. This way, we have only few codes in the derived class. The derived class inherits all those data members common in the base class and simply creates new ones that are specific to it and where necessary modifies the member functions of the base class to gain appropriate functionality.


Note that the when an object of the derived class is instantiated, the program will call its constructor of derived class to initialize its data members. This action will trigger a series of calls for constructors of base classes. If the derived class inherits directly from the base class, the constructor of the base class will be called to initialize its members in the derived class. After it has executed, it will hand over the control to the derived class to complete initialization. In our example above, newStaff was instantiated as an object of the HospitalStaff which is a derived class of HospitalCommunity. For this reason the constructor for the HospitalCommunity was called and it executed first and then handed over the control to the constructor of the HospitalStaff.

If the derived class inherits from a base class which in turn inherits from another base class, a series of constructors in their order of hierarchy will be called to initialize their members. The last to be called and the first to finish execution will be the constructor at the base of the hierarchy. The next in the hierarchy from the bottom will execute until the control is handed back to the derived class constructor whose object has been instantiated.

In the case of destructors, the process works in the reverse order in which the constructors execute. The base class destructor performs its task first and then calls the distractor of the base class from which it has a direct inheritance. This also performs its work and calls the next one in the hierarchy. The last to execute is the one at the base of the hierarchy.





PREV:Introduction to Operator Overloading

NEXT:update