Government Polytechnic , Nandurbar Subject: OOP
Unit-3 Extending Classes using Inheritance
3.1 Introduction to Inheritance
The mechanism of deriving a new class from an old one is called inheritance or derivation.
The old class is referred to as the base class and the new one is called the derived class or
sub class. The derived class inherits some or all of the traits from the base class.
A class can also inherit properties from more than one class or from more than one
level. Reusability is an important feature of OOP.
Reusability is feature of OOP.
We could reuse reuse something that already exists rather than trying to create
the same all over again.
It would not only save time and money but also reduce reliability.
The reuse of a class that has already been tested, debugged and use many time
can save us the effort of developing and testing the same again
Concept of reusability
C++, a new class can reuse the property of existing class
The mechanism of deriving a new class from old class is known as
inheritance.
Derived class inherits some or all the properties from base class
A class can also inherit properties from more than one level
Base Class(old)
Derived Class(new)
Page 1
Government Polytechnic , Nandurbar Subject: OOP
Defining a Derived class:
A derived class can be defined by specifying its relationship with the base class in addition to
its own details.
Syntax:
class derived-class-name : visibility-mode base-class-name
……… //member of derived class
………
The colon indicates that the derived class name is derived from the base-class-name. the
visibility mode is optional and if present, may be either private or protected or public.
The default is private. Visibility mode specifies whether the features of the base class
are privately derived or publicly derived.
Example :
class ABC : private XYZ //private derivation
{
members of ABC;
};
class ABC: public XYZ //public derivation
{
members of ABC;
};
class ABC : protected XYZ // protected derivation
{
members of ABC;
};
class ABC : XYZ //private by default
{
members of ABC;
};
Page 2
Government Polytechnic , Nandurbar Subject: OOP
When a base class is privately inherited by a derived class, public members of
the base class can only be accessed by the member functions of the derived class. private
member of base class are inaccessible to the objects of the derived class
When a base class is protected inherited by a derived class, public members of
the base class can only be accessed by the member functions of the derived class, private
members of base class are inaccessible to the objects of the derived class. If private
members of base class are to be inherited to derived class then declare them as protected
When the base class is publicly inherited, public members of the base class is
publicly inherited, public members of the base class become public members of the
derived class and therefore they are accessible to the objects of the derived class. In both
the cases, the private members are not inherited and therefore, the private members of a
base class will never become the members of its derived class
In inheritance, some of the base class data elements and member functions are
„inherited‟ into the derived class. We can add our own data and member functions and
thus extend the functionality of the base class. Inheritance, when used to modify and
extend the capability of the existing classes, becomes a very powerful tool for
incremental program development
When a base class is privately inherited by a derived class , ‘public member
’ of the base class become ‘private member ‘ & The public member of the
base class can only be access by the member function of the derived class .
Public member of a class can be accessed by its own objects using dot
operator and public member of base class become public member of derived
class in public inheritance
No member of the base class is accessible to the object of the derived class.
Private member are not inherited and private member of a base class will
never become the member of its derived class
Making private member inheritance:
What can be done if the private data needs to be inherited by a derived class.
This can be achieved by modifying the limit of the private member by making
it public.
C++ provide 3rd visibility made protected
A member declare under protected is accessible by the member function
within its class and any class immediately derived from it.
It can not be accessed by the function outside these two classes.
When a protected member is inherited in public mode, it become protected in
the derived class and accessible by the member function of the derived class.
Page 3
Government Polytechnic , Nandurbar Subject: OOP
Protected member , inherited in the private mode derivation become private in
the derived class.
Class alpha
private: //visible to member function within it class
-----------
-----------
protected: //visible to member functions of its own & derived class
-----------
-----------
public: //visible to all functions in the program
------------
------------
Page 4
Government Polytechnic , Nandurbar Subject: OOP
Visibility of inherited member:
Base Class
visibility Derived Class Visibility
Public Private Protected Derivation
Derivation Derivation
Private Not Inherited Not Inherited Not Inherited
Protected Protected Private Protected
Public Public Private Protected
Page 5
Government Polytechnic , Nandurbar Subject: OOP
Type of inheritance:
a) Single Inheritance
b) Multiple Inheritance
c) Hierarchical Inheritance
d) Multilevel Inheritance
e) Hybrid Inheritance
Single Inheritance
one derived class inherits from only one base class. It is the mostsimplest form
of Inheritance.
// Base class
// Derived class
Example : Illustrate program shows a Base class B and derived Class D
The class B contains one private data member, one public data member
and three public member function
The Class D contains one private data member and two public member
function.
Page 6
Government Polytechnic , Nandurbar Subject: OOP
Program for single inheritance
#include <iostream>
using namespace std;
class B
int a;
public:
int b;
void get_ab();
int get_a(void);
void show_a(void);
};
class D : public B
int c;
public:
void mul(void);
void display(void);
};
//============================
void B :: get_ab(void)
a=5;
b=10;
int B :: get_a()
return a;
Page 7
Government Polytechnic , Nandurbar Subject: OOP
void B :: show_a()
cout<<"a= "<<a<<"\n";
void D :: mul()
c=b*get_a();
void D :: display()
cout<<"a= "<<get_a()<<"\n";
cout<<"b= "<<b<<"\n";
cout<<"c= "<<c<<"\n\n";
//====================================
int main()
D d;
d.get_ab();
d.mul();
d.show_a();
d.display();
d.b=20;
d.mul();
d.display();
return 0;
Page 8
Government Polytechnic , Nandurbar Subject: OOP
Output :
a= 5
a= 5
b= 10
c= 50
a= 5
b= 20
c= 100
Multilevel Inheritance:
In this type of inheritance the derived class inherits from a class, which in turn inherits from
some other class. The Super class for one, is sub class for the other
A derive class with multilevel inheritance is declared as follows
Syntax :
Class A {……..}
Class B: public A {……..}
Class C: public B {……..}
This process can be extended to any number of level
Assume that the test results of a batch of students are stored in three different classes.
Class student stores the roll-number, class test stores the marks obtained in two
subjects and class result contains the total marks obtained in the test.
The class result can inherit can the details of the marks obtained in the test and the
roll-number of students through multilevel inheritance.
Page 9
Government Polytechnic , Nandurbar Subject: OOP
Program for Multilevel Inheritance:
#include <iostream>
using namespace std;
class student
protected:
int roll_number;
public:
void get_number(int);
void put_number(void);
};
void student :: get_number(int a)
roll_number=a;
void student :: put_number()
cout<<"Roll number: "<< roll_number<<"\n";
class test : public student //first level derivation
protected:
float sub1;
float sub2;
public:
void get_marks(float,float);
Page 10
Government Polytechnic , Nandurbar Subject: OOP
void put_marks(void);
};
void test :: get_marks(float x,float y)
sub1=x;
sub2=y;
void test :: put_marks()
cout<<"Marks in sub1="<<sub1<<"\n";
cout<<"Marks in sub2="<<sub2<<"\n";
class result : public test // Second level derivation
float total; // private by default
public:
void display(void);
};
void result :: display(void)
total=sub1+sub2;
put_number();
put_marks();
cout<<"Total="<<total<<"\n";
int main()
Page 11
Government Polytechnic , Nandurbar Subject: OOP
result student1;
student1.get_number(111);
student1.get_marks(75.0,59.5);
student1.display();
return 0;
Output:
Roll number: 111
Marks in sub1=75
Marks in sub2=59.5
Total=134.5
Multiple Inheritance:
In this type of inheritance a single derived class may inherit from two or more than two base
classes
A B
A class can inherit the attribute of two or more classes as shown in fig.
this is known multiple inheritance
Multiple inheritance allow us to combine the features of several existing classes as a
starting point for defining new classes.
It’s like a child inheriting the physical features of one parent and the intelligence of
another
Page 12
Government Polytechnic , Nandurbar Subject: OOP
Syntax of derived class with multiple base class :
Class D : visibility B1 , visibility B2….
-------------visibility may be either public or private
-------------
-------------
} ;
Program for Multiple Inheritance :
#include <iostream>
using namespace std;
class M
protected:
int m;
public:
void get_m(int);
};
class N
protected:
int n;
public:
void get_n(int);
};
Page 13
Government Polytechnic , Nandurbar Subject: OOP
class P: public M, public N
public:
void display(void);
};
void M :: get_m(int x)
m=x;
void N :: get_n(int y)
n=y;
void P ::display(void)
cout<<"m="<<m<<"\n";
cout<<"n="<<n<<"\n";
cout<<"m*n="<<m*n<<"\n";
int main()
P p;
p.get_m(10);
p.get_n(20);
p.display();
cout<<"Hello World";
Page 14
Government Polytechnic , Nandurbar Subject: OOP
return 0;
Output:
m=10
n=20
m*n=200
Hello World
Hierarchical Inheritance:
Inheriting is a method of inheritance where one or more derived classes is derived from
common base class.
B C D
We have discussed so for how inheritance can be used to modify a class when it did
not satisfy the requirements of a particular problem on hand.
Additional member are added through inheritance to extend the capabilities of a class.
Another interesting application of inheritance is to use it as a support to the
hierarchical design of a program.
Many programming problems can be cast into a hierarchical design of a problem.
Page 15
Government Polytechnic , Nandurbar Subject: OOP
Program for hierarchical:
#include<iostream>
using namespace std;
class A //Base Class
public:
int a,b;
void getnumber()
cout<<"\n\nEnter Number :\t";
cin>>a;
};
class B : public A //Derived Class 1
public:
void square()
getnumber(); //Call Base class property
cout<<"\n\n\tSquare of the number :\t"<<(a*a);
};
class C :public A //Derived Class 2
public:
void cube()
Page 16
Government Polytechnic , Nandurbar Subject: OOP
getnumber(); //Call Base class property
cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
};
int main()
B b1; //b1 is object of Derived class 1
b1.square(); //call member function of class B
C c1; //c1 is object of Derived class 2
c1.cube(); //call member function of class C
Enter Number : 2
Square of the number : 4
Enter Number : 2
Cube of the number ::: 8
Page 17
Government Polytechnic , Nandurbar Subject: OOP
Hierarchical classification of students:
Student
Engineering Medical
Mechanical Computer MBBS
Fig shows a hierarchical classification of students in a university
All the students have certain things in common
In C ++ , such problem can be easily converted into class hierarchies
The base class will include all the features that are common to the subclasses
A subclasses can be constructed by inheriting the properties of the base
A sub class can serve as a base class for the lower level classes and so on
Page 18
Government Polytechnic , Nandurbar Subject: OOP
Hybrid Inheritance:
Hybrid inheritance is combination of two or more inheritances such as
single, multiple, multilevel or Hierarchical inheritances.
B C
Program for hybrid Inheritance:
#include <iostream>
using namespace std;
class student
protected:
int roll_number;
public:
void get_number(int a)
roll_number=a;
void put_number(void)
cout<<"Roll Number:"<<roll_number<<"\n";
Page 19
Government Polytechnic , Nandurbar Subject: OOP
};
class test: public student
protected:
float part1, part2;
public:
void get_marks(float x , float y)
part1=x;
part2=y;
void put_marks(void)
cout<<" Marks obtain:"<<"\n"
<<"part1="<<part1<<"\n"
<<"part2="<<part2<<"\n";
};
class sport
protected:
float score;
public:
void get_score(float s)
Page 20
Government Polytechnic , Nandurbar Subject: OOP
score=s;
void put_score(void)
cout<<"Sport wt:"<<score<<"\n\n";
};
class result: public test , public sport
float total;
public:
void display(void);
};
void result :: display(void)
total=part1+part2+score;
put_number();
put_marks();
put_score();
cout<<"Total score: "<<total<<"\n";
int main()
result student_1;
student_1.get_number(1234);
student_1.get_marks(27.5,33.0);
Page 21
Government Polytechnic , Nandurbar Subject: OOP
student_1.get_score(6.0);
student_1.display();
return 0;
Output:
Roll Number:1234
Marks obtain:
part1=27.5
part2=33
Sport wt:6
Total score: 66.5
Ambiguity Resolution in Inheritance:
Occasional , we may face a problem using the multiple inheritance , when a function
with the same name appears in more than one base class
Consider the following two classes
Same function name in multiple classes =ambiguity
scope resolution operation is ambiguity resolution
Example : Ambiguity Resolution:
Class M
public :
void display( void )
cout<<“class M\n”;
};
Page 22
Government Polytechnic , Nandurbar Subject: OOP
Class N
{
public
void display( void)
{
cout<<“class N \n”;
}
};
Which display( ) function is used by the derived class when we inherit these two
classes
We can solve this problem by define a named instance within the derived class , using
the class resolution operator with the function
Class P : public M , public N
{
public:
void display( void) //overrides display( ) of M &N
{
M : : display( );
}
};
Page 23
Government Polytechnic , Nandurbar Subject: OOP
Ambiguity may also arise in single inheritance application:
Class A
{
public :
void display( )
{
cout<<“A \n”;
}
};
Class B : public A
{
public :
void display ( )
{
cout<<“B \n”;
}
};
In this case , the function in the derived class overrides the inherited function and
- a simple call to display ( ) by B only.
However , we may invoke the function define in A by using the scope resolution
operator to specify the class
Int main ( )
{
Bb; // derived class object
b.display( ); // invoked dispay( ) in B
b.A :: display ( ); //……………..in A
b.B :: display( ); // ………………in B
return 0;
}
Page 24
Government Polytechnic , Nandurbar Subject: OOP
This will produce the following output
Output: B
A
B
Virtual Base class:
We have just discussed a situation which would require the use of both the multiple
and multilevel inheritance.
Consider a situation where all the three kind of inheritance namely multiple ,
multilevel and hierarchical inheritance are involved.
The child has two direct base classes ‘ Parent1’ and ‘parent2’ which themselves have
a common base class ‘Grandparent’.
The ‘child’ inherits the traits of ‘Grandparent’ via two separate path.
It can also inherit directly as shown by the broken line.
The ‘ Grandparent ‘ is some time referred to as indirect base class.
Page 25
Government Polytechnic , Nandurbar Subject: OOP
Inheritance by the ‘child’ as in fig might pose some problem . All the public and
protected members of ‘Grandparent’ are inherited into ‘child’ twice. First via
‘parent1’ and ‘parent2’.
This means , ‘child’ would have duplicate set of the members inherited from
‘Grandparent’.
The introduces ambiguity and should be avoided.
The duplication of inherited members due to these multiple path can avoided by
making the common base class.
As virtual base class while declaring the direct or intermediate base class
Class A // Grandparent
……….……….
};
Class B1: virtual public A //parent1
……….……….
};
Class B2 : public virtual A // parent2
…………………….
};
Class C : public B1 , public B2 // child
………... //only one copy of A will be inherited
Page 26
Government Polytechnic , Nandurbar Subject: OOP
When a class is made a virtual base class , C++ take necessary care to see that only
one copy of that class is inherited , regardless of how many inheritance path exist
between the virtual base class and a derived class.
The keyword virtual and public may be used in either order.
Example : consider again the student - result processing system discussed
Assume that the class sports derives the roll_number from the class student.
Program to implement the concept of virtual base class:
#include <iostream>
using namespace std;
class student
protected:
int roll_number;
public:
void get_number(int a)
roll_number=a;
void put_number(void)
cout<<"Roll Number:"<<roll_number<<"\n";
};
class test: virtual public student
protected:
float part1, part2;
Page 27
Government Polytechnic , Nandurbar Subject: OOP
public:
void get_marks(float x , float y)
part1=x;
part2=y;
void put_marks(void)
cout<<" Marks obtain:"<<"\n"
<<"part1="<<part1<<"\n"
<<"part2="<<part2<<"\n";
};
class sport: public virtual student
protected:
float score;
public:
void get_score(float s)
score=s;
void put_score(void)
cout<<"Sport wt:"<<score<<"\n\n";
Page 28
Government Polytechnic , Nandurbar Subject: OOP
};
class result: public test , public sport
float total;
public:
void display(void);
};
void result :: display(void)
total=part1+part2+score;
put_number();
put_marks();
put_score();
cout<<"Total score: "<<total<<"\n";
int main()
result student_1;
student_1.get_number(1234);
student_1.get_marks(27.5,33.0);
student_1.get_score(6.0);
student_1.display();
return 0;
Output:
Roll Number:1234
Page 29
Government Polytechnic , Nandurbar Subject: OOP
Marks obtain:
part1=27.5
part2=33
Sport wt:6
Total score: 66.5
Constructor in derive class:
If base class constructor does not have any argument the derived class need not have a
constructor function.
If base class contains one or more arguments then it is mandatory for the derived class
to have a constructor and pass the arguments to the base constructor.
In inheritance we create object of any derived class , so it makes scenes for the
derived class to pass arguments to the base class constructor.
When both the base and derived class contains constructors the base constructor is
executed first and then the constructor in the derived class is executed
In multiple inheritance , the base classes are constructor in the order in which they
appear in the declaration of the derived class
The constructor of the derived class receives the entire list of value as its arguments
and passes them on to the base constructors in order they are declared in derive
Program for constructor in derived class
#include <iostream>
using namespace std;
class alpha
int x;
public:
alpha(int i)
Page 30
Government Polytechnic , Nandurbar Subject: OOP
x=i;
cout<<"alpha initialized \n";
void show_x(void)
cout<<"x="<<x<<"\n";
};
class beta
float y;
public:
beta(float j)
y=j;
cout<<"beta initialized\n";
void show_y(void)
cout<<"y="<<y<<"\n";
};
class gamma: public beta ,public alpha
Page 31
Government Polytechnic , Nandurbar Subject: OOP
int m,n;
public:
gamma(int a,float b,int c,int d):
alpha(a) , beta(b)
m=c;
n=d;
cout<<"gamma initialized\n";
void show_mn(void)
cout<<"m="<<m<<"\n"
<<"n="<<n<<"\n";
};
int main()
gamma g(5,10.75,20,30);
cout<<"\n";
g.show_x();
g.show_y();
g.show_mn();
cout<<"Hello World";
return 0;
Page 32
Government Polytechnic , Nandurbar Subject: OOP
Output:
x=5
y=10.75
m=20
n=30
Hello World
Page 33