Chapter04(g)
Chapter04(g)
4.1 INTRODUCTION:
“The mechanism of deriving new class from an already existing class is called inheritance.”
The old class is referred to as the Base class and new class is referred to as the Derived class.
The derived class inherits some or all features of the base class. Derived class can also add its own features.
The Base class remains unchanged in this process..
The main advantages of inheritance are the code reusability.
The following figure shows the inheritance relation ship between base class and derived class.
Feature A Defined in
Feature D
derived class
Feature B
Feature A
Defined in base
class but
Feature C Feature B
accessible in
derived class
Feature C
ADVANTAGES OF INHERITANCE:
Permits code Reusability:
Once the base class is written and debugged, it needs not to be touched again. One can create a new class, which
is derived from the base class. The newly derived class can inherit all the capabilities of base class and can also
add its own features to the base class to work in different manner without making any changes to the base class.
Reusing the existing code saves time and money and also increase program readability.
Inheritance also helps in original conceptualization of a programming problem, and in the overall design of the
program.
1
CHAPTER 4
3) class A : AB // By default private derivation
{
};
Ques : Explain three visibility modes ( Access-specifiers) available in C++.
int b; Inherited from base class, member function of derived class and
object of derived class can access it
public: int d;
void setdata ( int x ,int y )
{
b=x ; // ok
c = y; // ok
}
void display()
3
CHAPTER 4
{
cout << a; //error
cout << b <<c <<d; //ok
}
};
void main()
{
derived d1;
d1.set ( 10,20); //OK b =10 , c =20
d1.d =40; // will work b’cos d is a public member of class derived
d1.b = 50 ; // ok , b is now public member of derived class , object can access it.
}
TYPES OF INHERITANCE
1) Single Inheritance
2) Multiple Inheritance
3) Hierarchical Inheritance
4) Multi-Level Inheritance
5) Hybrid Inheritance.
Single Inheritance:
The inheritance in which there is one base class and one derived class is called single inheritance.
(One base class and one derived class)
Person
Employee
Multiple Inheritance:
Inheritance in which there is One derived class with several base classes is called multiple inheritance. (Several Base
classes and only one derived class)
Employee Emp_union
Emp_info
Hierarchical Inheritance
One base class may be inherited by several derived classes is called Hierarchical Inheritance.
(One base class several derived classes)
Employee
Multi-Level Inheritance:
A derived class can be derived from another derived class is called Multi level inheritance.
Student
Tests
Result
4
CHAPTER 4
Hybrid Inheritance.
The mechanism of implementing more than one type of inheritances is called Hybrid inheritance.
For e.g. following diagram implements Multiple as well as multilevel inheritance.
Student
Tests Sports
Result
SINGLE INHERITANCE (One base class and one derived class)
Class base-class-name
{
// body of base class
};
class derived-class-name : visibility-mode base-class-name
{
// body of derived class
};
Program base on single inheritance:
Declare base class ‘furniture’ having data member’s length, width and height. From that derive a class ‘bookshelf’
having data members as no f shelves.
#include <iostream.h>
class furniture
{
private: int l , w, h ;
public: void getdata (void)
{ cout << “Enter length” ;
cin>>l;
cout <<”Enter width “;
cin>>w;
cout << “Enter height “;
cin >>h;
}
void showdata (void)
{ cout << “length = “ <<l <<endl;
cout << “Width = “<< w <<endl;
cout << “Height = “ << h <<endl ;
}
};
class bookshelf : public furniture
{
int no_shelf;
public: void getdata (void)
{ furniture :: getdata();
cout << “Enter no. of shelves “;
cin >> no_shelf;
}
void showdata (void)
{ furniture :: showdata();
cout << “No. of shelves = “<< no_shelf;
}
};
void main(void)
{
bookshelf b1;
5
CHAPTER 4
b1.getdata();
b1.showdata();
}
OUTPUT :
Enter length 70
Enter width 30
Enter height 10
Enter no of shelves 8
Length =70
Width = 30
Height =10
No. of shelves =8
Identify the type of inheritance and implement it by writing a program for the following figure.
7
CHAPTER 4
Hierarchical Inheritance:
Syntax of hierarchical Inheritance:
class A // base class
{
// body of base class
};
class B : public A // derived class 1
{
// body of derived class 1
}
class C : public A // derived class 2
{
// body of derived class 2
}
Write a program to implement the following figure also identify the type of inheritance.
Class name : employee
Member variables: Emp_name , emp_id
8
CHAPTER 4
class worker : public employee // worker is derived from class employee
{
private :float over_sal;
public:void getdata (void)
{ employee :: getdata ();
cout << “Enter overtime salary : “
cin >>over_sal;
}
void showdata (void)
{ employee :: showdata ();
cout << “Over Time salary = “ << over_sal;
}
};
void main ()
{
manager m1 ; // create an object of manager
cout << “Enter details of manager “<<endl;
m1.getdata ();
m1.showdata ();
worker w1 ; // create an object of worker
cout << “Enter details of worker “<<endl;
w1.getdata();
w1.showdata();
}
OUTPUT
Enter eetails of manager
Enter emp id : 123
Enter emp name : Dinesh
Enter additional allowance : 5000
Emp id = 123
Emp name = Dinesh
Additional allowance = 5000
Enter details of worker
Enter emp id : 234
Enter emp name : Nitin
Enter over time salary : 300
emp id = 234
emp name = Nitin
over time salary = 300
Assignment:
Create a class publication that stores the title and price. From this class ,derive two classes : book and audio_cassette.
book will have ‘author’ as additional data member and audio_cassette will have ‘playing_time’ as additional data
member. Each of these classes sholud have getdata() and showdata() functions to accept and display details .Write a
program to implement the above inheritance.
Program based on Multiple inheritance: (several base classes and one derived class)
Syntax of multiple inheritance:
int main()
{
C obj;
Obj.show(); // ambiguity error: will not work
Obj . A::show() ; // OK Invokes show() of class A
Obj . B::show() ; // OK Invokes show() of class B
return 0;
}
In the above program the statement, obj.show();
Will report ambiguity error this is because class C has two base classes- class A and class B. And both the base classes
have the same function show (). The derived class C does not override the function show (). So compiler tries to
invoke the base class function, but here there are two versions of base class function 1) A:: show() 2) B::show().
Compiler cannot make decision which version is to call.
11
CHAPTER 4
Class : Student
Member variables: Name ,rollno
Class : test
Member variables: marks1 , marks2
Class : result
Mmeber variables :Toatal_marks
# include <iostream.h>
class student
{
private : int rollno;
char name[30];
public: void getdata(void)
{ cout <<”Enter rollno: “ << endl;
cin>>rollno;
cout << “Enter name : “<<endl
cin >> name;
}
void showdata(void)
{ cout <<”Rollno= “ <<rollno << endl;
cout << “Name = “<< name << endl;
}
};
class test : public student
{
protected : int marks1 , marks2; // merks1 and marks2 are protected members
public :void getmarks ()
{ cout << “Enter marks of sub1 : “ ;
cin >> marks1;
cout << “Enter marks of sub2 : “ ;
cin >> marks2;
}
void showmarks (void)
{
cout << “Marks of sub1 = “ << marks1;
cout << “Marks of sub2 = “<< marks2;
}
};
class result : public test
{
private : int total_marks;
public:void display_result()
12
CHAPTER 4
{
total_marks = marks1 + marks2; // marks1 and marks2 are accessible
// here b’cos they are declared as
// protected in base class test
student :: showdata();
test :: showmarks () ;
cout << “Total Marks = “<< total_marks;
}
};
void main()
{
result r1;
r1.getdata(); // get rollno and name
r1.getmarks(); // get marks1 and marks2
cout << “details of student: “ <<endl;
r1.display_result();
}
OUTPUT
Enter Rollno : 123
Enter Name : Deepali
Enter Marks of sub1: 45
Enter Marks of sub2 : 38
Details of student :
RollNo = 123
Name = Deepali
Marks of sub1 : 45
Marks of sub2
15
CHAPTER 4
{ B() ; ordinary base class const
}; A() : derived calss const
4) C() ; virtual base class const
class A : private B , virtual public C , virtual D (); virtual base class const
public D B() : ordinary base class const
{ A() ; Derived class const.
};
The constructor for virtual base class is invoked before the non- virtual base classes. If there are more than one
virtual base class them they are invoked in the order in which they are declared.
NOTE: Destructors are called in reverse order that is the most derived class destructor is invoked first and works
towards base class.
ABSTRACT CLASSES:
An abstract class is one that is not used to create any object. An abstract class is designed only to act as a base
class which can be inherited by other classes.
Consider the following example
class employee
{
};
class manager :public employee
{
};
class scientist :public employee
{
};
class laborer :public employee
{
};
In the above example employee acts as an abstract class. It is not used to create objects; it acts as a base class and
is inherited by manager, scientist, and laborer classes.
One way to make any class abstract is to place at least one pure virtual function in a base class. Now if you try to
create an object of that class, compiler will report an error.
class employee // abstract class
{
public:
virtual void display()= 0; // pure virtual fucntion
};
NOTE : pure virtual function is a function with no body .
VIRTUAL BASE CALSS:
The duplication of inherited members due to these multiple paths can be avoided by making the common
base class (ancestor class) as virtual base class while declaring the direct or intermediate base class.
Consider a situation where all three kinds of inheritance multiple, multilevel and hierarchical are involved.
Here in the above diagram the child has two direct base classes ‘ parent1’ and ‘parent2’ which themselves have a
common base class ‘grandparent’.
Grandparent
Parent 1 Parent2
Child
The ‘child’ class inherits the traits of ‘grandparent’ via two separate paths. All the public and protected members
of ‘grandparent’ are inherited twice via ‘parent1’ and again via ‘parent2’.
This means ‘child’ class would have duplicate sets of members inherited from ‘grandparent’ this introduces
ambiguity& should be avoided.
To avoid duplication of inherited members due to the multiple paths we use virtual base classes.
Consider the following example,
16
CHAPTER 4
# include <iostream.h>
class A // grandparent
{
};
class B1 : virtual public A // parent1
{
};
class B2 : virtual public A //parent2
{
}
class C : public B1 , public B2 // child
{
// only one copy of a will be inherited
};
When a class is made a virtual base class, C++ compiler takes necessary care to see that only one copy of that class is
inherited.
17