0% found this document useful (0 votes)
3 views

CH. 5 Inheritance

Uploaded by

sakshikamble8516
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CH. 5 Inheritance

Uploaded by

sakshikamble8516
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 118

Inheritance

In C++, it is possible to inherit attributes and methods from one class to


another. We group the "inheritance concept" into two categories:
derived class (child) - the class that inherits from another class
base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the attributes and
methods from the Vehicle class (parent):
Child class: The class that inherits the characteristics of another class is
known as the child class or derived class. The number of child classes
that can be inherited from a single parent class is based upon the type
of inheritance. A child class will access the data members of the parent
class according to the visibility mode specified during the declaration
of the child class.
Parent class: The class from which the child class inherits its properties is
called the parent class or base class. A single parent class can derive
multiple child classes (Hierarchical Inheritance) or multiple parent classes
can inherit a single base class (Multiple Inheritance). This depends on the
different types of inheritance in C++.
class parent_class
{
//class definition of the parent class
};
class child_class : visibility_mode parent_class
{
//class definition of the child class
};
class Vehicle { int main() {
public: Car myCar;
string brand = "Ford"; myCar.honk();
cout << myCar.brand + " " + myCar.model;
void honk() { return 0;
cout << "Tuut, tuut! \n" ; }
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
Introduction :
• Inheritance is a form of software reusability in which new classes are
created from existing classes by absorbing their attributes and behavior
and overriding these with capabilities the new classes requires.
• Inheritance is the process by which one object can acquire the
properties of another object.
• Inheritance is the process of creating new classes from existing class.
• The existing class is known as base class and the newly created class is
called as a derived class.
• The derived class inherits all capabilities of the base class.
• A derived class is more specific than its base class and represents a
smaller group of objects.
• For example, a Red Delicious apple is part of the classification apple,
which in turn is part of the fruit class. Hence, inheritance supports the
concept of classification; with the help of classification, an object
need to define only those qualities that makes it unique within its
class.
• Fig.: ‘Shape’ Hierarchy
Shape

Two Dimensional Shape Three Dimensional


shape

Shape Cube Tetrahedron


Circle Square Triangle
Advantages of Inheritance:
• It helps to implement software reusability. Once the hierarchy is done,
this specific data to the particular class can be added as per the
specification of the derived classes in hierarchy. Reusing existing code
saves time and money.
• It increase the reliability of the code.
• Inheritance can also help in the original conceptualization of a
programming problem and in the overall design of the program.
• It is useful to avoid redundancy, leading to smaller models that are
easier to understand.
• It adds some enhancement to the base class.
• We can create new class based on base class without modifying base
class.
Access Modifiers and Inheritance: Visibility of Class Members
Depending on Access modifier used while inheritance, the availability of class
members of Super class in the sub class changes. It can either be private,
protected or public.

1) Public Inheritance
This is the most used inheritance mode. In this the protected member of super
class becomes protected members of sub class and public becomes public.

class Subclass : public Superclass

2) Private Inheritance
In private mode, the protected and public members of super class become private
members of derived class.

class Subclass : Superclass // By default its private inheritance


3) Protected Inheritance
In protected mode, the public and protected members of Super class becomes
protected members of Sub class.

class subclass : protected Superclass

Types of Inheritance :
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Inheritance :
• When one base class is derived by one child class, then it is known as single
inheritance.
• The existing base class is known as direct base class whereas, they newly
created class is called as singly derived class. As shown in Fig. :
• Single Inheritance is the most primitive among all the types of inheritance in
C++. In this inheritance, a single class inherits the properties of a base class.
All the data members of the base class are accessed by the derived class
according to the visibility mode (i.e., private, protected, and public) that is
specified during the inheritance.
#include <iostream>

using namespace std;


class electronicDevice
{
public:
electronicDevice()
{ cout << "I am an electronic device.\n\n"; }
};

class Computer: public electronicDevice

{public:
Computer()
{ cout << "I am a computer.\n\n"; }
};

int main()

{ Computer obj;
return 0; }
class base_class_1
{ // class definition };
class derived_class: visibility_mode base_class_1
{ // class definition };
Example :
Suppose a college want to store information of undergraduate (UG) and
Postgraduate students (PG). Both are having registration number , name
and address. Each postgraduate student also have additional attributes
along with above attributes areUGStudent
placement company name.
As shown in Fig. :- Regno
Name
address

PGStudent

Companyname
• Program to illustrate single inheritance.
#include<iostream.h>
using namespace std;
class student
{
protected :
int regno;
char name[20];
char addr[30];
public :
void getdata()
{ cout<<“Enter registration no, name and address ”;
cin>>regno>>name>>addr;
}
void display() void dispPG()
{ {
cout<<“registration no. =”<<regno; cout<<“\n Registration no. =”<<regno;
cout<<“name = ”<<name; cout<<“\n Name =”<<name;
cout<<“address = ”<<addr; cout<<“\n Address =”<<addr;
} cout<<“\n Company name
=”<<compname;
};//end of base class
}
class PGstudent : public student
};
{ int main()
private : {
char compname[20]; student s;
public : PGstudent ps;
void get_PG_data() s.getdata();
{ s.display();
getdata(); ps.get_PG_data();
ps.dispPG();
cout<<“\n Enter the Company name :”;
}
cin>>compname;
}
}
• Output :-
Enter registration no , name and address
10 Ram Pune
registration no = 101 name = Ram addr = Pune
Enter registration no , name and address
402 Sita Pune
Enter Company Name = Zenex
registration no = 402
name = Sita
address = Pune
Company Name = Zenex
• Program : A base class contains the data of employee name, empno and
Gender. The derived class has been declared as an array of class objects.
The Program illustrate the Single inheritance.
class derived : public base
#include<iostream.h>
{
class base private :
float bsalary;
{ public:
private : void get();
void disp();
char name[20]; };
int empno; void base :: get()
{
char gender; cout<<“\n Enter name :”;
Public : cin>>name;
cout<<“\n Enter Employee id :” ;
void get(); cin>>empno;
void disp(); cout<<“\n Enter Gender :”;
cin>>gender;
}; }
void base:: disp()
void main()
{ {
cout<<“name =”<<name; derived ob[10];
cout<<“Emp no. is =”<<empno; int i,n;
cout<<“Gender =”<<gender; cout<<“How many employees ?”;
cin>>n;
} for(i=0;i<n;i++)
void derived:: get() {
{ ob[i].get();
base:: get(); }
cout<<endl;
cout<<“Enter basic salary :\n”;
cout<<“Name empno gender bsalary \
cin>>bsalary; n”;
} for(i=0;i<n;i++)
void derived:: disp() {
ob[i].disp();
{
cout<<endl;
base::disp(); }
cout<<“basic salary =”<<bsalary; }
}
Output :
How many employees? 2
Enter name: Prajakta
Enter Employee id :101
Enter Gender :f
Enter basic salary : 10000
Enter name: Pratik
Enter Employee id : 102
Enter Gender :m
Enter basic salary :40000
name empno gender bsalary
Name=Prajakta Empno is = 101 sex=f basic salary=10000
Name=Pratik Empno is = 102 sex=m basic salary=40000
2. Multilevel Inheritance :-

• When a base class is derived by a child class which further derived by


another child class, then it is known as Multilevel Inheritance.
• The class which provides link between two classes is known as
intermediate base class. As shown in fig. :Multilevel Inheritance.
• Practically, we can have more than two levels also.
base class

Intermediate base class


child class1

child class 2
• Syntax of multilevel inheritance :
class base
{ ………….
…………
};
class child1: public base
{ ……………….
……………….
};
class child2: public child1
{ ……………………….
……………………….
};
• Consider an example of bank. In bank, different customers have
savings account. Some customers may have taken loan from the bank.
So the bank always maintains information about bank depositors and
borrowers. This can be shown using the following Fig. :
customer
name
phone_no

depositor
account_no
balance

borrower
loan_no
Loan_amount
• Program to illustrate use of multilevel inheritance.
#include<iostream.h>
using namespace std; void get_depositor_data()
{
class customer //base class cout<<“\n Enter nme & phone no”;
{ cin>>name>>phone_no;
cout<<“\n Enter account no and
protected: balance”;
char name[30]; cin>>account_no>>balance;
}
int phone_no;
void display_depositor_data()
}; //end of base class {
class depositor: public customer//child class1 cout<<“\n Name = ”<<name;
cout<<“\n Phone no =”<<phone_no;
{ cout<<“\n Account no =”<<account_no;
private : cout<<“\n Balance = ”<<balance;
}
int account_no; }; //end of child class1
float balance;
public :
class borrower : public depositor //child class2
{
protected :
int loan_no;
float loan_amount;
public :
void get_loan_data()
{
cout<<“\n Enter loan no and loan amount”;
cin>>loan_no>>loan_amount;
}
void display_loan_data()
{
cout<<“\n Loan no = ”<<loan_no;
cout<<“\n Loan amount =”<<loan_amount;
}
};
int main()
{
int choice;
cout<<“1-Read & display depositor information ”<<endl;
cout<<“2-Read & display depositor & borrower information”<<endl;
cout<<“Enter your choice =” ;
cin>>choice;
switch(choice)
{
case 1:
depositor d;
d.get_depositor_data();
d.display_depositor_data();
break;
case 2: Output :-
borrower b; 1- Read & display depositor information
2- Read & display depositor & borrower
b.get_depositor_data(); information
b.get_loan_data(); Enter your choice = 1
Enter name & phone no Prajakta 98776677
b.display_depositor_data(); Enter account no and balance 123456789
b.display_loan_data(); 10000
break; Name = Prajakta
Phone no = 98776677
} Account no = 123456789
}// end of main Balance = 10000
• In this program, though the data members of depositor class are
private, they can accessed indirectly by the borrower class through
the member functions of the depositor class indirectly.
• Consider the example of student data. Base class is student. Class test is intermediate base class and
result is child class. The class result inherits the details of marks obtained in the test and the roll no.
of student from base class through multilevel inheritance.
#include<iostream.h> class test : public student
{
using namespace std;
protected :
class student int mark1, mark2;
{ public :
protected : void getmark(int a, int b)
{
int roll; mark1 = a;
public : mark2 = b;
void get(int x) }
void dispmark()
{
{
roll = x; cout<“mark1 = \n”<<mark1<<“mark2=\n”<<mark2;
} }
void display() };
{
cout<<“roll=”<<roll;
}
};
class result: public test int main()
{ {
result r;
private:
r.get(10);
int total; r.getmark(60,75);
public: r.displayall();
void displayall() }
Output:
{
total = mark1 + mark2; roll = 10
display(); mark1 = 60
mark2 = 75
dispmark(); total = 135
cout<<“total=” <<total;
}
};
3. Multiple Inheritance :-
• When more than one base classes are inherited by a derived class, then such
type of inheritance is called as multiple inheritance.
• The inheritance in which a class can inherit or derive the characteristics of
multiple classes, or a derived class can have over one base class, is known as
Multiple Inheritance.
• It specifies access specifiers separately for all the base classes at the time of
inheritance. The derived class can derive the joint features of all these classes
and the data members of all the base classes are accessed by the derived or
child class according to the access specifiers.
• Fig. : Multiple Inheritance
• Example : A child inherits the features from father and intelligence
form mother.
Mother Father
Intelligence Features

Child
Features Intelligence

Fig. : Multiple Inheritance


• Syntax of Multiple Inheritance :
1. Multiple inheritance with all public derivation :
class base1
{// class definition
};
class base2
{ // class definition
};
class derived_class: public base1, public base2
{ // class definition
};
Here, access specifier may be public or private and the base classes are
separated by commas
2. Multiple inheritance with all private derivation :
class base1
{// class definition
};
class base2
{ // class definition
};
class derived_class: private base1, private base2
{ // class definition
};
3. Multiple inheritance with all mixed derivation :
class base1
{// class definition
};
class base2
{ // class definition
};
class base3
{
//class definition
};
class derived_class: public base1, public base2, private base3
{ // class definition
};
• Program for Multiple Inheritance.
class derived : public basex, public basey
#include<iostream.h>
{
using namespace std; public :
class basex void display()
{ {
cout<<“x = ”<<x<<“\n”;
protected:
cout<<“y = ”<<y<<“\n”;
int x; cout<<“x +y= ”<<x+y<<“\n”;
public :
void get_x(int a) }
};
{ x = a; } int main()
}; {
Class basey derived ob;
{ ob.get_x(50);
ob.get_y(60);
protected : ob.display();
int y; }
public : Output:
void get_y(int b) x = 50
y = 60
{ y=b; } x + y = 110
};
• Consider an example to print bio-data of a diploma student having personal and academic information. Program to illustrate use of multiple
inheritance.
#include<iostream.h>
using namespace std;
class person1
{
private:
char name[30], email_id[50];
protected:
void get_personal_info()
{
cout<<“\n Enter name & email id of a person = ”;
cin>>name>>email_id;
}
void display_personal_info()
{
cout<<“\n Name = ”<<name;
cout<<“\n Email_id = ”<<email_id;
}
};//end of base class1
class academic
{ private: else
if(tenth_marks>=50)
float tenth_marks;
strcpy(tenth_class, “Second class”);
char tenth_class[20]; else
protected: if(tenth_marks>=40)
void get_academic_info() strcpy(tenth_class, “Pass class”);
else
{
strcpy(tenth_class,”Fail”);
cout<<“\n Enter tenth marks”; }
cin>>tenth_marks; void display_academic_info ()
} {
void find_class()
cout<<“\n Tenth marks = ”<<tenth_marks;
find_class();
{
cout<<“\n Tenth class = ” ;
if(tenth_marks>=70) cout<<tenth_class;
strcpy(tenth_class, “Distinction”);
else }
}; //end of base class2
if(tenth_marks>=60)
strcpy(tenth_class, “First class”);
class bio_data:private personal, private academic // Derived class
{
void display_biodata(); int main()
{
void get_info(); bio_data b;
//First read info
};//end of derived class b.get_info();
// Now print biodata
//Member fuctions of derived class b.display_biodata();
void bio_data::display_biodata() }
Output :
{ Enter name & email id of a person = Prajakta abc@yahoo
Enter tenth marks 80.5
cout<<“BIODATA”<<endl; BIO DATA
cout<<“personal info = ” <<endl; Personal info =
Name = Prajakta
display_personal_info(); Email_id = abc@yahoo
Academic info =
cout<<“Academic info = ” <<endl; Tenth marks = 80.5
display_academic_info(); Tenth class = Distinction

}
Ambiguity in Multiple Inheritance :
• One common cause of ambiguity in multiple inheritance is when two or
more base classes have methods with the same name, while there is no
method of that name in the derived class.
• In this case objects of the derive class have no way of knowing which of
the parent method is to be executed. The scope resolution operator can
be used to resolve the ambiguity.
• Another element of ambiguity in multiple inheritance arises when two
or more derived classes inherit the same member from a common base
class. If now another derived class inherits from these classes, two
copies of the original member function could be inherited.
• Fig. shows one possible scenario that leads to inheritance of multiple
copies.
Base1

Method(1)

Derived1 Derived 2

Method1() Method1()

Derived3

Method1()
Method1()???

Fig. :Inheritance of Multiple Copies


• One possible solution to this duplicity is the use of the scope
resolution operator. Another solution of this problem is to declare the
base classes to be virtual at the time of they are inherited.
• Advantages of Multiple Inheritance :-
1. Derived class typically represents a combination of its base classes.
2. It has rich semantics.
3. It has ability to directly express complex structures.
4. Hierarchical Inheritance :-
• When one base class is inherited by more than one derived classes, it
is known as hierarchical inheritance.
• In this, many programming problems can be cast into a hierarchy
where certain features of one level are shared by many other below
that level.
• The Fig. : Hierarchical Inheritance :
Base class2

Derived class1 Derived class 2 ………. Derived class n


• Syntax of Hierarchical Inheritance :-
class base
{
…….
…….
};
class derived1: public base
{
……..
………
};
class derived2: public base
{
…………………
…………………
};
• Example : Consider an example of an organization having full time and
part time employees. Depending on it, the employee salary is
calculated. The hierarchy is :
• Employee
name

Full -Time Part-time


daily_rate no_of_hours
no_of_days hourly_rate
salary salary
• Program to illustrate use of hierarchical inheritance.
#include<iostream.h>
using namespace std; void full_time_emp::read_emp_data()
{
class employee //base class cout<<endl<<“Enter name of employee =”;
{ cin>>name;
protected: cout<<endl<<“Enter working rate for one day =” ;
char name[30]; cin>>daily_rate;
}; //end of base class cout<<endl<<“Enter no. of working days of employee =”;
cin>>no_of_days;
class full_time_emp : protected employee
}
{ void full_time_emp::calculate_salary()
protected : {
float daily_rate, salary; salary = daily_rate*no_of_days();
int no_of_days; }
public :
void read_emp_data();
void display_emp_data();
void calculate_salary();
}; //end of derived class1
void full_time_emp ::display_emp_data()
{
cout<<endl<<“For the full time employee =”;
cout>>”Name =“<<name;
cout<<endl<<“Daily rate =” <<daily_rate;
cout<<endl<<“No. of working days =”<<no_of_days;
cout>>endl<<“Salary =”<<salary;
}
class part_time_emp:protected employee //derived class2
{
protected:
float hourly_rate, salary;
int no_of_hours;
public :
void read_emp_data();
void display_emp_data();
void calculate_salary();
}; //end of derived class2
void part_time_temp::read_emp_data()
{
cout<<endl<<“Enter name of employee=”;
cin>>name;
cout<<endl<<“Enter working rate for one hour =”;
cin>>hourly_rate;
cout<<endl<<“Enter no. of working hours for employee =” ;
cin>>no_of_hours;
}
void part_time_emp:calculate_salary()
{
salary = hourly_rate*no_of_hours;
}
void part_time_emp:display_emp_data()
{
cout<<endl<<“For the part time employee”;
cout<<endl<<“Name =”<<name;
cout<<endl<<“Hourly rate =”<<hourly_rate;
cout<<endl<<“No. of working hours =”<<no_of_hours;
cout<<endl<<“salary=” <<salary;
}
int main()
{
int choice;
cout<<endl<<“You have following choices” ;
cout<<endl<<“1.-Read & display information of full time employee”;
cout<<endl<<“2.-Read & display information of part time employee”;
cout<<endl<<“Enter your choice =”; Output :
cin>>choice; You have following choices :
switch(choice) 1.-Read & display information of full time
{ case 1: full_time_emp ft; employee
//first read data
2.-Read & display information of part time
employee
ft.read_emp_data();
Enter your choice =1
ft.calculate_salary();
Enter name of employee = Prajakta
//Now display data Enter working rate for one day = 250
ft.display_emp_data(); Enter no. of working days of employee = 30
break;
case 2: part_time_emp pt; For the full time employee :=
//first read data Name=Prajakta
Daily rate = 250
pt.read_emp_data();
No. of working days = 30
pt.calculate_salary();
Salary = 7500
//Now display data
pt.display_emp_data();
break; }
• In the above program, both derived classes have same names for the
member functions. You can also use different names.
• Also in the above program, you can use array of objects to store
information about more than one employee.
5. Hybrid Inheritance :-
• Sometimes, we may require to combine two or more types of
inheritance to design a program; the result is known as Hybrid
Inheritance. Fig. : Hybrid Inheritance.
Base class
Base class

Derived class1 Derived class2 Derived class1 Derived class2

Derived class3 Derived class2


• Example : Consider an example where we have three classes student,
test and result. But some authority wants some weightage should be
given for sports to finalize the result. This is shown in Fig.:
Student

test sports

result

Fig. : Hybrid Inheritance (Multiple and Multilevel)


• Program for Hybrid Inheritance.
#include<iostream.h> class test :public student
class student {
{
protected:
int mark1, mark2;
protected :
public :
int rollno; void getmark(int a, int b)
public : {
void get(int x) mark1 = a;
{ rollno = x; mark2 = b;
} }
void display()
void dismark()
{
{
cout<<mark1<<“ “<<mark2;
cout<<rollno; }
} };
};
class result: public test, public sport void main()
{ {
private : result r;
int total; r.get(10);
public : r.getmark(50,60) ;
void displaytotal() r.getsm(70);
{ r.displaytotal();
total = mark1 + mark2 + smark; }
display(); Output :
dispmark(); 10 50 60 70
disps(); Total = 180
cout<<“total = ” <<total;
}
};
• Base Class and Derived Class Examples :-
• In C++, a class that is inherited is referred to as a base class. The class
that does the inheriting is called derived class.
• A derived class can be defined by specifying its relationship with the
base class. The pictorial representation of single inheritance is shown
in Fig. :
Base class

Derived class

Fig. Base class and Derived class


• Some example of inheritance is shown in Table :
• Table : Examples of inheritance
Base Class Derived Class
Shape Circle
Triangle
Rectangle
Employee Teacher
Clerk
Media Book
Tape
Student Undergraduate
Postgraduate

• When a class inherits another, the member of the base class becomes members of the
derived class.
• The Syntax of derived class definition is as follows :
class <derived_class_name >: <access modifier> <base_class_name>
{
//body of class
};
It contains:
• Keyword class
• Derived class name which is user defined name for new class.
• The : (colon) indicates that the derived_class_name is derived from the
base_class_name.
• The access modifier is optional. If no access modifier is present, the access
modifier is private by default . If written, then it must be public, private or
protected.
• base_class_name is the existing class name.
• Example:-
class base class derived:base //by default private
{…………………………. derivation
{ ………………………..
………………………….. ……………………….
}; };
class derived1: private base //private derivation
{
………………….
};
class derived2: public base //public derivation
{
………………….
};
class derived2: protected base //protected derivation
{
………………….
};
• Public Derivation :
• When the access modifier for a base class is public, all public
members of the base class become public members of the derived
class and all protected members of the base class becomes protected
members of the derived class.
• The members of derived class can access members of the base class if
the base class members are public or protected. They can not access
private members.
• The Fig. shows the base and derived class relationship.
Private
Class derived : public base
Protected

Base Public Private


object

Protected

Access member
function of base Public

Derived object

Fig. : Public Derivation


• Program to demonstrate public derivation. class derived : public base
#include<iostream.h> {
int k;
using namespace std; public :
class base void getdata()
{ {
getij();
int i,j;
cout<<“Enter value of k”;
public : cin>>k;
void getij() cout<<“k=” <<k;
}
{ cout<<“Enter value of i and j”;
};
cin>>i; int main()
cin>>j; {
} base ob1; //base object
derived ob2; //derived object
void show() ob1.getij(); //access member of base class
{ ob1.show(); //display values of I and j
cout<<“i=”<<i<<“j=”<<j<<“\n”; ob2.getdata(); //access member of derived class
ob2.show(); //access member of base class
} }
};
• Output :
Enter value of i and j 2 3
i=2 j=3
Enter value of i and j 5 6
Enter value of k 7
K=7 i=5 j=6
• In this program, the base class members are directly access through derived
class, because the derived through derived class and derived class is
publicity derived from base class.
• In inheritance some of the base class data elements and member functions
are inherited into the derived class which extends the capability of the
existing classes and useful in incremental program development. If the
function names of the base and derived class are same then use scope
resolution operation(::) and show the scope of the function i.e. to which the
class that function belongs.
• Write a program to read data member of a base class i.e. name , person id and the derived class members
are height and weight. Display the data of person.
#include<iostream.h>
using namespace std;
class base
{
private :
char name[20];
int person_id;
public :
void getdata()
{
cout<<“Enter name and person_id”;
cin>>name>>person_id;
}
void display()
{
cout<<“name :”<<name<<“ ”<<“person_id:”<<person_id;
class derived: public base
{ int main()
private: {
int height, weight; derived obj;
public: obj.getdata();
void getdata() obj.display();
{
}
base:: getdata();
Output :
cout<<“Enter height and weight”;
Enter name and person_id Prajakta 11
cin>>height>>weight;
Enter height and weight 6 80
}
name : prajakta person_id : 11 height :6
weight : 80
void display()
{
base::display();
cout<<“height :”<<height<<“ ”<<“weight :”<<weight;
}
};
• Private Derivation :-
• When the base class is inherited by using the private access modifier,
all public and protected members of the base class become private
members of the derived class.
• The Fig. shows the private derivation of inheritance.
class base

Private Class derived : private base

Private
Protected
Access member
function of base
Base object Public Protected

Public
Not possible to access the
member function of base
class Derived object
• Program for private derivation.
#include<iostream.h>
using namespace std;
class Engine
{
public :
Engine(int nc)
{cylinder = nc;
}
void start()
{
cout<<getcylinder()<<“Cylinder engine started ”<<endl;
}
int getCylinder()
{
return cylinder;
}
private:
class Car : private Engine
{
public:
Car(int nc = 4): Engine(nc){ }
void start()
{
cout<<“car with ”<<Engine::getCylinder()<<“cylinder engine started ”<<endl;
Engine::start();
}
};
int main() • In this program, derived class object cannot access
{ the functions of base class because they become
private.
Car c(8); • But the public functions of base class access by public
c.start(); functions of derived class.
return 0;
}
Output:
car with 8 cylinder engine started
8 cylinder engine started
• Protected Members :
• The protected keyword provides greater flexibility in the inheritance
mechanism.
• When a member of a class is declared as protected, that member is
not accessible by other, non-member elements of program.
• Protected members are as good as private members within the class.
• Protected member differs from private members when a protected
member is inherited. Using the access modifier protected in base
class, we could make available the data member in the derived class
and restrict its access in other classes or in main().
• Protected members of base class can be access in derived class.

class base

private
Class derived :public class
protected

Base object private


public

protected
Access
members
Access members public
Derived object
• Data member declare as protected within a base class is
accessible by the member within its class and any class
immediately derived from it.
• Fig. shows the public derivation with protected data
members.
• If the base class is inherited as public, then the base class
protected member becomes protected member of derived
class and therefore, can be accessed by derived class.
• Thus, by using protected, we can create class members that
are private to their class but can still be inherited and
accessed by a derived class.
• Program using protected members.
#include<iostream.h>
using namespace std;
class base
{
protected :
int I,j; //private to base, but accessible by derived class
public :
void getij()
{
cout<<“\n Enter value of i and j”;
cin>>i>>j;
}
void show()
{
cout<<“i=”<<i<<“ “<<“j=”<<j<<“\n”;
}
};
class derived2: public derived1
class derived1 : public base {
int x;
{ public:
int k; void get()
{
public: getij();
x=i*j;
void getdata() } //can access I and j since public inheritance
{ void show()
{
getij(); cout<<“x=”<<x;
k=i*j; }
}; //end of class derived2
} int main()
{
void showx() derived1 ob1;
{ derived2 ob2;
ob1.getdata();
cout<<“k=”<<k; ob1.showlal() ;
ob2.get();
}
ob2.showx();
}; //end of class derived1 }
• Output:
Enter value of i and j 10 20
K=200
Enter value of i and j 15 10
K=150
• In above program, if derived1 class inherits base class privately, then
protected member of base becomes private members of derived1
class which cannot inherited in derived2 class.
• So, when a protected member is inherited in public mode, it
becomes protected in the derived class and therefore it is accessible
by the member function of the derived class. It is also inherited
further.
• A Protected member inherited in the private mode becomes private
in the derived class and cannot be inherited further.
• Protected Derivation :-
• C++ allows us to use protected as access modifier.
• When access modifier is protected, all public and protected members of the base class become protected
members of the derived class.
• Program for protected derivation.
#include<iostream.h>
using namespace std;
class base
{
protected :
int i, j; //private to base but accessible in derived
public :
void getij()
{
cin>>i>>j;
}
void show()
{
cout<<i<<“ “<<j<<“\n”;
}
class derived: protected base int main()
{ {
derived ob;
int k; //ob.getij() //illegal; getij() is protected member of
public: derived
void getdata() ob.getdata(); //correct as public member of derived
ob.showall(); //correct as public member of derived
{
//ob.show(); //illegal
getij(); }
k = i*j; //derived may access base Output:
2 3
protected data members
6 2 3
}
void showall()
{
cout<<k<<“ “;
show();
}
};
• In this program, getij() and show() are public members of base, but
they become protected members of derived. Using derived object is
not accessible .
• Summary about Access Specifiers :
• Table : Access in a Derived Class
Derived class
Base class members Public derivation Private derivation Protected
derivation
Private Not accessible Not accessible Not accessible
Protected Protected Private protected
Public Public Private protected
• Virtual Base Class :-
• Consider a situation where multilevel, multiple and hierarchical all the
three kinds of inheritance are involved. As shown in fig. :
• Fig. : Multipath inheritance
base

derived1 derived2

derived3
• In this fig., the base class is inherited by both derived1 and derived2.
derived3 directly inherits both derived1 and derived2.
• All the public and protected members of Base are inherited into
derived3 twice through both derived1 and derived2.
• Therefore, derived3 would have duplicate sets of members inherited.
This causes ambiguity when a member of Base is used by derived3.
• To resolve this ambiguity, C++ includes a mechanism by which only
one copy of Base will be included in derived3. This feature is called a
virtual base class. When a class is made virtual, C++ take necessary
care to inherit only one copy of that class.
• The keyword virtual precedes the base class access specifier when it is
inherited by a derived class.
• The situation in Fig. can be declared as :
Class base
{……………};
Class derived1:virtual public Base
{…………..};
Class derived2: virtual public Base
{……………};
Class derived3: public derived1, public derived2
{……………};
class derived2: virtual public base
• Program using virtual base class. {
public:
#include<iostream.h> int z;
};
using namespace std; /*derived3 inherits derived1 and derived2.
However, only one copy of base is present. */
class base class derived3: public derived1, public derived2
{ {
public :
public: int mult()
{ return x*y*z;};
int x; };
void main()
}; {
derived3 d;
class derived1: virtual public base d.x = 10;
{ d.y = 20;
d.z = 30;
public : cout<<“Product is”<<d.mult();
}
int y; Output :
Product is 6000
};
• Note :
• If derived1 and derived2 classes had not inherited base as virtual,
then statement d.x = 10; becomes ambiguous and a program would
have resulted as compile-time error.
• If virtual base classes are used when an object inherits the base more
than once, only one base class is present in the object.
• If normal base classes are used when an object inherits the base more
than once, the multiple copies will be found; and it is compile error.
• Program: To calculate the total marks of a student using the concept of virtual base class.
#include<iostream.h>
using namespace std;
class student
{
int rno;
public:
void getnumber()
{
cout<<“Enter Roll No.”;
cin>>rno;
}
void putnumber()
{
cout<<“\n\n Roll No. :”<<rno<<“\n”;
}
};
class test : virtual public student
{ class sports : public virtual student
public : {
int part1, part2; public :
void getmarks() int score;
{ void getscore
cout<<“Enter Marks\n”; {
cout<<“Part1 :” ; cout<<“Enter Sports Score :”;
cin>>part1; cin>>score;
cout<<“Part2 :”; }
cin>>part2; void putsccore()
} {
void putmarks()
cout<<“\n\t Sports score is :”<<score;
{
}
cout<<“\t Marks Obtained \n”;
};
cout<<“\n\t Part1 :”<<part1;
cout<<“\n\tPart2 :”<<part2;
}
};
class result : public test , public sports int main()
{
{ result obj;
obj.getnumber();
int total; obj.getmarks();
public: obj.getscore();
obj.display();
void display() }
Output:
{ Enter Roll No.:151
total = part1 + part2 +score; Enter Marks
Part1: 90
putnumber(); Part2: 80
Enter sports score :80
putmarks(); Roll No. :151
putscore(); Marks Obtained
Part1 : 90
cout<<“\n\t Total Score :”<<total; Part2 : 80
Sports Score is :80
} Total Score is : 250
};
Abstract Class :-
• A class that contains at least one pure virtual function is said to be
abstract. A pure virtual function is a member function i.e., declared in
an abstract class, but defined in a derived class.
• An abstract class does not create any object and it contains one or
more functions for which there is no definition(i.e., pure virtual
function) .
• We can create pointers and references to an abstract class. This
allows abstract classes to support runtime polymorphism, which
depends upon base class pointers and references to select the proper
virtual function.
• An abstract class is used only to derive other classes. For example :
Shape is abstract base class which derives square, circle and rectangle.
• Following Program shows use of abstract classes.
#include<iosream.h>
using namespace std;
class Square : public Shape
//Abstract class
{
public :
class Shape
float calculateArea()
{
{ return l*l; }
protected:
};
float l;
int main()
public :
{
void getData() Square s;
{ Circle c;
cin>>l; cout<<“Enter length to calculate the area of a square :”;
} s.getdata();
//virtual function cout<<“Area of square :”<<s.calculateArea();
virtual float calculateArea() = 0; cout<<“\n Enter radius to calculate the area of a circle :”;
}; c.getData();
class circle: public Shape cout<<“Area of circle :”<<c.calculatearea();
{ return 0;}
public :
Output:
float calculateArea()
Enter length to calculate the area of a square : 4
Area of square : 16
{
Enter length to calculate the area of a circle : 5
return 3.14*l*l;
Area of circle : 78.5
Polymorphism:
• Polymorphism means “one name , many forms”.
• Polymorphism is the process of defining a number of objects at
different classes into group and call the method to carry out the
operation of the objects using different function calls.
• There are two types of polymorphism :
1. Compile time polymorphism :
• This is also called as early or static binding .Selection of an
appropriate function for a particular call at the compile time itself.
• For example, function overloading and operator overloading .
• Function overloading is also referred to as functional polymorphism.
• The same function can perform a wide variety of tasks.
• The same function can handle different data types. When many
functions with the same name but different argument lists are
defined ,then the function to be invoked corresponding to a function
call is known during compile time.
• When the source code is compiled, the functions to be invoked are
bound to the compiler during compile time, as to invoke which
function depending upon the type and number of arguments . Such a
phenomenon is referred to early binding, static linking or compile
time polymorphism.
2. Run-time polymorphism:
• This is also called as dynamic binding or late binding.
• Sometimes, a situation occurs where function name and prototype is same
in both the base class and in the derived class.
• Compiler does not know what to do, which function to call.
• In this class appropriate member function is selected to run time.
• For example, virtual function.
• Fig. : Types of Polymorphism Polymorphism

Compile time Polymorphism Run-time Polymorphism

Function Overloading Operator Virtual Functions


Overloading
Virtual Functions and Pure Virtual Functions :
• Virtual Functions :-
• Virtual function is member function that is declared within base class
and redefined by a derived class.
• A virtual function is declared by preceding the function declaration in
the base class with the keyword virtual.
• Example :virtual void show(); //show function is virtual.
• When virtual functions access normally , it behaves just like any other
type of class member function. However, virtual function is used to
support runtime polymorphism when it is accessed via a pointer.
• A base class pointer can be used to point to an object of any class
derived from that base.
• When different objects are pointed to different versions of the virtual
functions are executed.
• Program for virtual functions.
#include<iostream.h>
class base
{
public:
virtual void display()
{ cout<<“This is base virtual function \n”;}
};
class derived1 : public base
{
public:
void display()
{ cout<<“This is derived1 virtual function \n”; }
};
class derived2: public base
{
void display()
{cout<<“This is derived2 virtual function \n”; }
};
void main()
{
base * p, b; //p is base class pointer and b is object of base
derived d1;
derived d2; • Output :
p = &b; //point to base This is base virtual function
This is derived1 virtual function
p->display(); //access base function
This is derived2 virtual function
p->&d1; //point to derived1
p->display(); //access derived1 function
p = &d2; //point to derived2
p->display(); //access derived2 function
}
Rules for Virtual Function :
• The virtual function must be member of same class.
• Virtual functions are accessed by using object pointers.
• They cannot be static members i.e. must be non-static members.
• The prototype of the base class version of a virtual function and all the
derived class versions must be identical.
• We can have virtual destructors but do not virtual constructors.
• We cannot use a pointer to a derived class to access object of the base type
i.e. reverse is not true.
• If a virtual function is defined in the base class, it need not be necessarily
redefined in the derived class.
• A virtual function can be a friend of another class.
• Because of the restrictions and differences between function overloading
and virtual function redefinition, the term overriding is used to describe
virtual functions redefinition by a derived class.
Pure Virtual Functions :-
• Most of the times, the virtual function inside the base class is rarely used for
performing any task. It only serves as a placeholder.
• Such a functions are called do nothing functions; which are pure virtual
functions.
• A pure virtual function is a virtual function that has no definition within the
base class.
• Syntax :
virtual <return_type> <function_name> <arg_list> = 0;
• When a virtual function is made pure, any derived class must provide its own
definition.
• If the derived class fails to override the pure virtual function, compile time
error will occur.
• A class containing such a pure virtual function is called an Abstract class.
• We can define pure virtual functions as “The functions which
are only declared but not defined in the base class are called
as pure virtual function”.
Properties of Pure Virtual functions :
• A pure virtual function has no implementation in the base
class, hence a class with pure virtual function cannot be
instantiated.
• A pure virtual member function can be invoked by its derived
class.
• It is just placeholder for derived class.
• The derived class is supposed to fill this empty function.
• Program for a pure virtual function.
#include<iostream.h>
using namespace std;
class number
{
protected :
int val;
public :
void set_val(int i)
{
val = i;
}
virtual void show() = 0; //pure virtual function
};
class hextype: public number class octtype: public number
{
{ public :
void show()
public : {
void show() cout<<oct<<val<<“\n”;
}
{ cout<<hex<<val<<“\n”; };
int main()
} {
}; dectype d;
hextype h;
class dectype: public number octtype o;
d.set_val(20); //displays 20-decimal
{ d.show();
public : h.set_val(20); //displays 14-hexadecimal
h.show();
void show() o.set_val(20); //displays 24- octal
{ cout<<val<<“\n”; o.show();
return 0;
} }
Output :
}; 20 14 14
• In the above program, as shown the base class, number contains an
integer called val, the function setval() and the pure virtual function
show().
• The derived classes hextype, dectype and octtype inherit number
and redefine show() so that it outputs the value of val in each
respective number base(i.e. hexadecimal, decimal or octal).
OVERRIDING :
• If derived class defines same function as defined in the base class, it is
known as function overriding in C++. It is used to achieve runtime
polymorphism.
• It is often useful for a derived class to define its own version of a
member function inherited from its base class. This may be done to
specialize the member function to the needs of the derived class .
• When this happens, the base class member function is said to be
overridden by the derived class.
• Because of the restrictions and differences between function
overloading and virtual function redefinition, the term overriding is used
to describe virtual functions redefinition(overridden) by a derived class.
• In simple words, the re-definition of a virtual function in a derived class
is usually called overriding.
• Program for overriding of member functions.
#include<iostream.h> int main()
using namespace std; {
class BaseClass DerivedClass obj = DerivedClass();
obj.disp();
{
return 0;
public: }
void disp() Output :
{ cout<<“Function of Parent Class ”;} Function of Child Class
};
class DerivedClass: public BaseClass
{
public :
void disp()
{cout<<“Function of Child Class ”;}
};
#include <iostream> class Linux_based : public electronicDevice, public Computer

using namespace std; {};

int main()
class electronicDevice
{ public: {

electronicDevice() // object of the derived class


{ cout << "I am an electronic device.\n\
n“: } Linux_based obj;
return 0;
};
class Computer }
{
public:
Computer()
{ cout << "I am a computer.\n\n";
}
};
Multi Level
In C++ programming, not only you can derive a class from the
base class but you can also derive a class from the derived class.
This form of inheritance is known as multilevel inheritance.
class A { ... .. ...
};
class B: public A {
... .. ...
};
class C: public B { ... ... ...
};
#include <iostream>
class C : public B { // derived from class derive B subclass
using namespace std;
private:
class A { // Base Class
int c;
public:
public:
int a;
void getdata_C()
void getdata_A()
{ cout << "Enter value of c: ";
{ cout << "Enter value of a: ";
cin >> c;
cin >> a;
}
}
void sum()
};
{
class B : public A { // derived class from base class A intermediate
int ans = a + b + c;
public:
cout << "sum: " << ans;
int b;
}
void getdata_B()
};
{ cout << "Enter value of b: ";
int main()
cin >> b;
{C obj; // object of sub class
}
};
obj.get_A_data();
obj.get_B_data();
obj.get_C_data();
obj.sum();
return 0;
}
In Hierarchical inheritance, more than one sub-class inherits the
property of a single base class. There is one base class and multiple
derived classes.
Hierarchical structures thus form a tree-like structure. It is similar to
that, mango and apple both are fruits; both inherit the property of
fruit. Fruit will be the Base class, and mango and apple are sub-classes.
In diagram ,Class A is a Base class, B is a subclass inherited from class A,
and C is a subclass it also inherits from class A.
Class A
{ ............
};
Class B: access_specifier A
{
.........
};
Class C: access_specifier A
{
#include <iostream>
using namespace std;
class person
{ char name[100],gender[10];
int age;
public:
void getdata()
{ cout<<"Name: ";
cin>>name;
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};
class student: public person
{ class employee: public person
char institute[100], level[20]; {
public: char company[100];
void getdata() float salary;
{ public:
person::getdata(); void getdata()
cout<<"Name of College/School: "; {
cin>>institute; person::getdata();
cout<<"Level: "; cout<<"Name of Company: ";
cin>>level; cin>>company;
} cout<<"Salary: Rs.";
void display() cin>>salary;
{ }
person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};
hybrid inheritance
Combining various types of inheritance like multiple, simple, and hierarchical inheritance is
known as hybrid inheritance.
In hybrid inheritance, there is a combination of one or more inheritance types. For instance, the
combination of single and hierarchical inheritance. Therefore, hybrid inheritance is also known as
multipath inheritance.

Single inheritance - Class B inherits class


A. Thus an example of single inheritance.

Multiple inheritance - Class D is inherited


from multiple classes( B and C shown
above D). Thus an example of multiple
inheritance.
class A

{ // block of statement(s)
}:

class B: public A // class B derived from a single class A -- follows single inheritance
{// block of statement(s)
};
class C
{// block of statement(s)
};
class D: public B, public C
// class D derived from two classes, class B and class C -- follows multiple inheritance
{
// block of statement(s)
};
#include <iostream> class Mammals: public Animals // indicates class B derived from
class A
using namespace std;
{
class Animals // indicates class A
public:
{
Mammals()
public:
{
Animals()
cout<< "This is a mammal\n";
{
}
cout<< "This is an animal\n";
};
}

};
class Cow: public Mammals, public Herbivores
class Herbivores // indicates class C
// indicates class D derived from class B and class C
{
{
public:
public:
Herbivores()
Cow()
{
{ cout<< "A cow is a herbivore mammal\n"; }
cout<< "This is a herbivore\n";
};
}
int main() {
};
Cow c;

return 0;

}
Virtual base class:
Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an
inheritance hierarchy when using multiple inheritances.

Need for Virtual Base Classes: Consider the situation where we have one class A . This class A is inherited by two other classes B
and C. Both these class are inherited into another in a new class D as shown in figure below.
As we can see from the figure that data members/function of class A are inherited twice to class D. One through class B and
second through class C. When any data / function member of class A is accessed by an object of class D, ambiguity arises as to
which data/function member would be called?
One inherited through B or the other inherited through C.
This confuses compiler and it displays error.

What is Virtual Class?


Virtual Class is defined by writing a keyword “virtual” in the derived classes,
allowing only one copy of data to be copied to Class B and Class C.
It prevents multiple instances of a class appearing as a parent class in the
inheritance hierarchy when multiple inheritances are used.

How to Declare Virtual Base Class in C++?


Syntax
If Class A is considered as the base class and Class B and Class C are considered
as the derived classes of A.
class student { class test : virtual public student {
int rno; public:
public: int part1, part2;

void getnumber() { void getmarks() {


cout << "Enter Roll No:"; cout << "Enter Marks\n";
cin>>rno; cout << "Part1:";
} cin>>part1;
cout << "Part2:";
void putnumber() { cin>>part2;
cout << "\n\n\tRoll No:" << rno << "\n"; }
}
}; void putmarks() {
cout << "\tMarks Obtained\n";
cout << "\n\tPart1:" << part1;
cout << "\n\tPart2:" << part2;
}
};
class sports : public virtual student { class result : public test, public sports {
public: int total;
public:
int score;
void display() {
void getscore() { total = part1 + part2 + score;
cout << "Enter Sports Score:"; putnumber();
putmarks();
cin>>score; putscore();
} cout << "\n\tTotal Score:" << total;
}
void putscore() { };
cout << "\n\tSports Score is:" << score;
void main() {
} result obj;
}; clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
Virtual function –
A virtual function is a member function which is declared within a base class and is
re-defined (overridden) by a derived class. When you refer to a derived class object
using a pointer or a reference to the base class, you can call a virtual function for
that object and execute the derived class’s version of the function.

Virtual functions ensure that the correct function is called for an object, regardless
of the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
• Rules for Virtual Functions

• Virtual functions cannot be static.


• A virtual function can be a friend function of another class.
• Virtual functions should be accessed using pointer or reference of base class
type to achieve runtime polymorphism.
• The prototype of virtual functions should be the same in the base as well as
derived class.
• They are always defined in the base class and overridden in a derived class. It is
not mandatory for the derived class to override (or re-define the virtual
function), in that case, the base class version of the function is used.
• A class may have virtual destructor but it cannot have a virtual constructor.
#include<iostream>
using namespace std; void show()
{
class base { cout << "show derived class\n";
public: }
virtual void print() };
{ int main()
cout << "print base class\n"; {
} base *bptr;
derived d;
void show() bptr = &d;
{
cout << "show base class\n"; bptr->print();
} bptr->show();
};
return 0;
class derived : public base { }
public:
void print()
{
cout << "print derived class\n";
}
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have implementation, But we must
override that function in the derived class, otherwise the derived class will also become abstract class . A pure virtual function
is declared by assigning 0 in declaration.
#include<iostream>
using namespace std; int main(void)
{
class Base Derived d;
{ d.fun();
int x; return 0;
public: }
virtual void fun() = 0;
int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
Abstract Class
A class that contains a pure virtual function is known as an abstract class.
We cannot create objects of an abstract class. However, we can derive classes from
them, and use their data members and member functions (except pure virtual
functions). // Derived 1
#include <iostream> class Square : public Shape {
using namespace std; public:
float calculateArea() {
class Shape {// Abstract class return dimension * dimension;
protected: }
float dimension; };

public: // Derived 2
void getDimension() { class Circle : public Shape {
cin >> dimension; public:
} float calculateArea() {
return 3.14 * dimension * dimension;
// pure virtual Function }
virtual float calculateArea() = 0; };
};
int main() {
Square square;
Circle circle;

cout << "Enter the length of the square: ";


square.getDimension();
cout << "Area of square: " <<
square.calculateArea() << endl;

cout << "\nEnter radius of the circle: ";


circle.getDimension();
cout << "Area of circle: " <<
circle.calculateArea() << endl;

return 0;
}
Function Overriding
In this tutorial, we will learn about function overriding in C++ with the help of
examples.

As we know, inheritance is a feature of OOP that allows us to create derived


classes from a base class. The derived classes inherit features of the base class.

Suppose, the same function is defined in both the derived class and the based
class. Now if we call this function using the object of the derived class, the
function of the derived class is executed.

This is known as function overriding in C++. The function in derived class


overrides the function in base class.
#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;
derived1.print();
return 0;
}

You might also like