Lesson06 Inheritance
Lesson06 Inheritance
Inheritance is a concept which is the result of commonality between classes. Due to this
mechanism, we need not repeat the declaration as well as member functions in a class if they
are already present in another class. For example, consider the classes namely “person” and
“employee”. All information that is present in the class person, will be present in the class
employee also. Apart from that, there will be some extra information in class employee due
the fact that an employee is person with some additional information introduced by the
employment status. With inheritance, it is enough only to indicate that information which is
specific to the employee in its class, and then inherit the common information from the class
person.
In a nutshell, an employee is a person with some additional information.
When we are declaring the classes person and employee without applying the concept of
inheritance, the two classes will look as follows:
class person
{
public:
string name, phone, email;
int age, idno;
};
class employee
{
public:
string name, phone,email;
int age, idno, empno;
float salary;
}
Now, without repeating the entire information of class person in class employee, we can
declare the employee class as follows:
class employee: public person
{
public:
int empno;
float salary;
};
Inheritance is the process by which objects of one class acquires the properties and methods
of another class. The class from which properties and methods are inherited is called base
class and the class to which they are inherited is called derived class. Inheritance can be
broadly classified into:
Single Inheritance
Multiple Inheritance
1
A. Irungu
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
2
A. Irungu
6.4 Hierarchical Inheritance
In hierarchical inheritance several classes can be derived from a single base class
3
A. Irungu
4. When the protected derivation mode is used, all public and protected members of the
base become protected members of the derived class.
5. In all cases, the private elements of the base class remain private to the base and are
not accessible by members of the derived class.
Example:
class Base {
public:
int x;
protected:
int y;
private:
int z;
};
#include <iostream>
using namespace std;
class animal
{
private:
int age;
protected:
string race;
public:
int color;
4
A. Irungu
};
class bird: public animal
{
};
class mammal: public animal
{
};
};
int main()
{
bat bxxx;
return 0;
}
5
A. Irungu