You are on page 1of 12

INHERITANCE

Inheritance is the ability of a new class to acquire the properties (data and functions/ methods)
of an existing class. It is one of the most powerful features of Object Oriented Programming.
The class created is referred to as the child or the derived while that from which it is created is
called the parent or base. Inheritance is basically used to support the concept of reusability.

Inheritance is used to model the "is-a" relationship where the derived class is a subtype of the
base class. This allows for code reuse of the shared characters, i.e., it is possible to derive a
class that has got all the functionality of a base class.

Additional data and functions can be added to the derived class and inherited functions can be
redefined in the derived class.

Types of inheritance
A class can inherit properties from more than one class or from more than one level. A
derived class with one base class, is called single inheritance and one with several base
classes is called multiple inheritance. On the other hand, the traits of one class may be
inherited by more than one class . This process is known as hierarchical inheritance. The
mechanism of deriving from another 'derived class' is known as multilevel inheritance. The
following figure shows forms of inheritance that could be used for writing extensible
programs. The direction indicates the direction of inheritance.

SMA2176 Computer Programming II Notes ~ A. Kamau Page 1 of 12


The derived class inherits all the functions of the base class except for constructors, destructors,
and the assignment operator (=).

Note: There are two complementary roles of inheritance


i). Specialization: - Is the extending the functionality of an existing class. It enables to add
functionality by extending what exists at each level of the class hierarchy to create more
specialized versions of the class.
ii). Generalization:- This is the sharing commonality between two or more class
Inheritance Syntax
class DerivedClass : kind BaseClass

Methods of Inheritance (Derivation)


There are three method of inheritance:
i). Public inheritance : Public and protected members of the base class remain, respectively,
public and protected members of the derived class.
The general syntax for deriving B from A is given by:-
Class B: public A

ii). Protected inheritance : Public and protected members of the base class are protected
members of the derived class.
The general syntax for deriving B from A is given by:-
class B: protected A

iii). Private inheritance : Public and protected members of the base class are private members
of the derived class.
The general syntax for deriving B from A is given by:-
class B : private A or class B : A

Note: In all cases, private members of a base class, remain private to the base class, are
private members of the derived class.

Example
The following is the base and derived class definition for manager class which inherits from
the employee class and which is illustrated in the diagram below:

Employees Manager

Name name
Id common id
Salary salary
New count
attribute

SMA2176 Computer Programming II Notes ~ A. Kamau Page 2 of 12


class Employee // base class
{
char * name;
int id;
float salary;
public:
Employee (/* parameters for Employee constructor */);
void print (void);
};

class Manager: public Employee // this indicates inheritance


{
short count;
public:
Manager (/* parameters for Manager constructor */);
void print (void);
};

Access Regions
A derived class may not have full access to all the base class. Access Regions could be
defined accordingly. There are, basically, three types of access regions private, protected and
public.
i). private:
Members can only be accessed by member or friend functions of their class.
ii). protected:
• Members can be accessed by member and friend functions of their class.
• Members can also be accessed by member and friend functions of the derived class.
iii). public:
Members are accessible from any part of the program.
Base Class Derived Class
Friends
can access
Public Derived
Section class has
access to
Friends both the
can access Protected public and
Section protected
members of
Friends the class.
no access Private
Section

SMA2176 Computer Programming II Notes ~ A. Kamau Page 3 of 12


Example:
Maliyamoto College requires a program to store and display the details of its employees and
students.
Required:
Using C++ write a program with the following specifications:
1. Person class that defines properties common to both students and employees. For
instance, age and first name.
2. Student class that is derived from the person’s class and is used to define properties that
further define a student. For instance aggregate grade and admission number.

#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
using namespace std;

class Person
{
protected: // accessible to derived classes
int age;
char first_name[50];
public:
void input()
{
cout<<"Enter the Age\t";cin>>age;
cout<<"Enter the First Name\t";
cin>>first_name;
}
};
//student inherits person.Notice the syntax.
class Student: public Person
{
private:
char admission_number[20];
char grade;
public:
void get_student_details(){
cout<<"Enter the admission number:\t";
cin>>admission_number;
cout<<"Enter the aggregate grade:\t";
cin>>grade;
}

void display_values()
{
cout<<"Students Details"<<endl;
//student can refer to person’s members as if they

SMA2176 Computer Programming II Notes ~ A. Kamau Page 4 of 12


//were part of student.
cout<<"Age:\t"<<age<<endl;
cout<<"First Name:\t"<<first_name<<endl;
cout<<"Admission Number:\t"<<admission_number<<endl;
cout<<"Grade:\t"<<grade<<endl;
}
};

int main()
{
Student stud;
/*all members of student are available to student objects
even those inherited from the person class.*/
stud.input();
stud.get_student_details();
system("cls");
stud.display_values();
return 0;
}
Syntax for the various form of Inheritance
Multilevel inheritance
A derived class with multilevel inheritance is declared as follows:
class A{ }; // Base class
class B: public A { }; // B derived from A
class C: public B { }; // C derived from B
This process can be extended to any number of levels.

Multiple Inheritance
Multiple inheritance allows to combine features of several existing classes and is declared as
follows:
class D: visibility B1, visibility B2……….
{
…………
…………(body of D)
…………
};

Constructors and Inheritance


When deriving from a base class, chances are good that the base class has a constructor or two.
If a base class constructor requires parameters, then the derived class is responsible for
providing the required values.
When the constructor for a derived-type object is called, the base class constructor is called
automatically during the initialisation phase of the derived class constructor. The base class
constructor code executes first.

SMA2176 Computer Programming II Notes ~ A. Kamau Page 5 of 12


Base Takes Care of Base; Derived Takes Care of Derived
When deriving, only initialise the members that are added by the derived class.
If any of the inherited base class constructors require parameters, the derived class constructors
must provide the necessary values using the initialisation list syntax.
Derived::Derived (parameter-list) : Base (values)
{
assignments
}
Incase of multiple inheritance, the base classes are constructed in the order in which they appear
in the declaration of the derived class. Similarly, in a multilevel inheritance, the constructors will
be executed in the order of inheritance

The constructors for virtual base classes are invoked before any non-virtual base classes. If the
are multiple virtual base classes, they are invoked in the order in which they are declared. Any
non-virtua1 bases are then constructed before the derived class constructor is executed as shown
below:

Example
Write a C++ program that contains an Employee class. The class contains data that is common
to any category of employees including permanent, contract and hourly employees, that is the
first name and last name and display() member function. You are further provided with the
following information regarding the hourly class. The class inherits from Employee class and
includes the data member wage and hours of type double. In addition the class implements the
member function getPay (), which calculates and return the amount of money to be paid to a
hourly worker and display(), which displays the first and the last name and the pay of the
hourly worker. Note that the pay of Hourly worker is the product of wage and number of hours.

#include<iostream>
#include<iomanip>
#include<cstring>
SMA2176 Computer Programming II Notes ~ A. Kamau Page 6 of 12
using namespace std;
class Employee{
public:
Employee(char [], char []);
void display();
private:
char first_name[20];
char last_name[20];
};
Employee::Employee(char first[],char last[])
{
strcpy(first_name,first);
strcpy(last_name,last);
}

// output the employee name


void Employee::display()
{
cout<<first_name<<" "<<last_name<<endl;
}

//Hourly class derives from Employee class


class HourlyWorker:public Employee
{
public:
HourlyWorker(char [],char[],double,double);
double getPay();
void display();
private:
double wage;
double hours;
};

HourlyWorker::HourlyWorker(char first[], char last[],


double hHours,double hWage):Employee(first,last)
{
hours=hHours;
wage=hWage;
}
void HourlyWorker::display()
{
// class the base class display to print names
Employee::display();
cout<<"Is a Hourly worker With a pay of KSh:"
<<setiosflags(ios::fixed|ios::showpoint)
<<setprecision(2)<<getPay()<<endl;
}

SMA2176 Computer Programming II Notes ~ A. Kamau Page 7 of 12


double HourlyWorker::getPay()
{
return hours*wage;
}

int main()
{
HourlyWorker Emp("Beth","Wakeen",20,500);
Emp.display();
return 0;
}

Exercise
The following diagram shows the relationship between classes. The details of each class are
given below.

STUDENT SPORTS

TESTS

RESULTS

The class STUDENT has the following details


• Name of the Student
• ID Number

The class of the tested students called TESTS, has the following details
• Marks for Programming
• Marks for Accounting Software
• Functions for inputting data
• Functions for displaying data

Class SPORTS has the following details


• Scores awarded
• Functions for inputting data
• Functions for displaying data

Finally the RESULTS class has the following details


• Total marks from tests and sports

SMA2176 Computer Programming II Notes ~ A. Kamau Page 8 of 12


• Functions for inputting data
• Functions for displaying data

Required:

Using the concept of INHERITANCE, write a complete C++ program that specifies the
above classes and a driver program that implements the same.
Note:
One of the greater advantages of deriving classes is that a pointer to a derived class is type-
compatible with a pointer to its base class.

POLYMORPHISM
The word literally means many forms. Basically it allows objects of different types to respond
differently to the same message and is one of characteristic of object-oriented programming.
C++ implements polymorphism with virtual functions.
Benefits of Polymorphism
i). Adding of new type does not require modification to existing code. Apart from saving time
in typing switch statements, dynamic binding is more extensible.
ii). One name can be used to refer to one concept, regardless of its implementation.

Virtual Functions
• A virtual function is a member function that is declared as virtual in the base class and
redefined in one or more derived classes.
• A class is extensible if it contains virtual functions. Capabilities can be added without access
to ancestor’s source code.
• Provide dynamic binding. The decision of which function to execute is put off until run time.

Note:
Early or static binding: the compiler determines which version of a method to invoke.
Using Virtual Functions
− Base and derived types have a member function with the same prototype.
− The name of the function, all parameter types and order, and return type must be identical.
− The function prototype is preceded with the keyword virtual.
− The decision is of which function to invoke is based on the type of the object that is being
pointed to or referenced. i.e. C++ determines which function to use at run time based on the
type of object pointed to by the base pointer, rather than the type of the pointer.
− Destructors can be virtual while constructor cannot be virtual.

SMA2176 Computer Programming II Notes ~ A. Kamau Page 9 of 12


Virtual Function Syntax
Declaration is just like any function prototype except that the word virtual is stated.
virtual return_type function_name (argument);
The following example illustrates how a function is declared virtual.

class Employee // base class


{ char * name;
int id;
float salary;
public:
Employee (/* parameters for Employee constructor */);
virtual void print (void);
};

class Manager: public Employee //this indicates inheritance


{
short count;
public:
Manager (/* parameters for Manager constructor */);
void add_employee (Employee *);
void print (void);
};

Rules for Virtual Functions


When virtual functions are created for implementing late binding, the following basic rules
should be observed to satisfy the compiler requirements:
1. The virtual functions must be members of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even though it may not be used.

Abstract Classes
• This is class that is not used to create objects but it can be used to declare a pointer type. It is
designed only to act as a base class (to be inherited by other classes). It is a design concept in
program development and provides a base upon which other classes may be built. There are
defined by declaring pure virtual functions, which are not defined, but assigned the value
zero.
E.g. virtual void display (void) = 0;

• When a class derives from an abstract class, the derived class may provide a definition for the
pure virtual function(s). If the derived class does not define the function(s), it, too, is an
abstract class.
• Generally pure virtual functions prevent instantiation.

SMA2176 Computer Programming II Notes ~ A. Kamau Page 10 of 12


Example :
#include <iostream>
#include <cstring>
using namespace std;

class GeneralDrawing
{
public:
virtual void draw (void)=0;
};
class Square : public GeneralDrawing
{
double side;
public:
Square (double s): side(s){}
void draw (void) { cout << "Square with size"<<side<< endl;}
};
class Rectangle: public GeneralDrawing
{
double width, height;
public:
Rectangle (double w, double h): width(w), height(h){}
void draw (void) {
cout << "Rectangle with width " << width<< "\t height "
<< height << endl;
}
};
int main()
{
Square room(33), den(44);
Rectangle hall(12, 44);
GeneralDrawing *shape[3];

int index = 0;
shape [0] = &room;
shape [1] = &den;
shape [2] = &hall;
while (index < 3)
{
shape [index++]->draw();
}
return 0;
}

In general abstract classes and virtual members grant to C++ the polymorphic characteristics that
make object-oriented programming such a useful instrument. Of course we have seen the
simplest way to use these features, but imagine these features applied to arrays of objects or
objects assigned through dynamic memory.

SMA2176 Computer Programming II Notes ~ A. Kamau Page 11 of 12


Exercise
Consider a book shop which sells both books and video-tapes. Use need to create a class known
as media that stores the title and price of a publication. Create two other classes, one for storing
the number of pages in a book and another for storing the playing time of a tape. All classes uses
constructors to initialize the data members and have a member functions display(), which is used
in all the classes to display the class contents. The classes are implemented in Program

MEMBER CLASSES/NESTING OF CLASSES


C++ supports yet another way of inheriting properties of one class into another. This approach
takes a view that an object can be a collection of many other objects. That is, a class can contain
objects of other classes as its members as shown below:

All objects of gamma class will contain the objects a and b. This kind of relationship is called
containership or nesting. A nested object is created in two stages. First, the member objects are
created using their respective constructors and then the other 'ordinary' members are created.
This means, constructors of all the member objects should be called before its own constructor
body is executed. This is accomplished using an initialization list in the constructor of the nested
class as shown in the example below:

x, y, z is the list of arguments that is to be supplied when a gamma object is defined. These
parameters are used for initializing the members of gamma. x is the argument list for, the
constructor of a and x,y is the argument list for the constructor of b. Notice that, a(x) and b(x,y)
are function calls and therefore the arguments do not contain the data types.

SMA2176 Computer Programming II Notes ~ A. Kamau Page 12 of 12

You might also like