Inheritance
One of the most useful and powerful feature of OOPS is inheritance.
The mechanism of deriving or creating new class from the old class is called
as Inheritance.
The new class is called as Derived class/subclass and old class is called as
Base class/super class.
E.g. As a child can inherit features of his/her parents ,in the same way one
class can inherit features of another class.
Inheritance provides code reusability and code extendibility.
To get the meaning of these above features consider one e.g.
Grand father Father Son
Have two floor Get two floor building Get three floor
building of his own from his father and add building from father
one more floor and add one more
floor.
Code
extend
Code
extend extend
Code
Code reuse
Reuse
So in the above e.g. let grandfather is base class ,father is derived from grand
father class and son is derived from both father and grand father class.
So here father class is also termed as intermediate base class because it is
base for son.
So by above e.g. code reusability and code extendibility features are well
explained.
Parent Base class
Child Derived class
In this technique the object of last derived class is declared .
The object of derived class is use to called member functions of derived class
as well as member functions of base class.
To access base class data member using derived class object , the base class
data members should be under protected access specifier.
Syntax for derived class definition:-
class derived_classname : access specifier base_classname
{
access specifier : list of data members;
access specifier : list of member functions();
}object name;
class grandfather //base class
{
protected : int i,j;
public: void get()
{
i=5; j=10;
}
};
class father : public grandfather //derived class1 and base class2
{
protected: int k;
public: void get1()
{
get();
k=20;
}
};
class son : public father //derived class 2
{
private : int t;
public: void display()
{
get1();
t= i+j+k;
}
}obj;
void main()
{
clrcsr();
[Link]();
getch();
}
So in the above program grandfather is base class1, father is derived class and also
intermediate base class2 and son is derived class2 .
Son class is derived from both grandfather and father class.
The object of only son class is declared i.e. obj.
As son is publicly derived from both the class, it can have access to public member
function and protected data members of both the class. So in display () function it
can call get1() function without using object. And also get1() function can call get()
function wihout using object. And also derived class i.e. son uses protected data
members of both the class i.e. i,j,k.