0% found this document useful (0 votes)
12 views25 pages

Polymorphism Part2 - Inheritance & Virtual Classes

The document explains the concept of inheritance in programming, detailing its types including single, multilevel, multiple, hierarchical, and hybrid inheritance. It provides examples and code snippets to illustrate how classes can inherit properties and methods from other classes, simplifying code reuse and organization. Additionally, it addresses the diamond problem in inheritance and introduces the solution of virtual base classes to prevent ambiguity and duplication of base class members.

Uploaded by

kagochibana4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views25 pages

Polymorphism Part2 - Inheritance & Virtual Classes

The document explains the concept of inheritance in programming, detailing its types including single, multilevel, multiple, hierarchical, and hybrid inheritance. It provides examples and code snippets to illustrate how classes can inherit properties and methods from other classes, simplifying code reuse and organization. Additionally, it addresses the diamond problem in inheritance and introduces the solution of virtual base classes to prevent ambiguity and duplication of base class members.

Uploaded by

kagochibana4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

POLYMORPHISM

Part2: Inheritance & Virtual Functions


Inheritance
❖ Inheritance is a technique of re-using data members and member functions of an existing class into
another class.
❖ Instead of beginning from scratch, an existing class can be inherited and additional data members and
member functions can be defined.

This makes programming easier because:

❖ we can reuse code


❖ we avoid repeating the same members in many classes
❖ we can build specialized classes from general ones

The class being inherited is called:

• base class or
• super class or
• parent class

The class that inherits is called:

• derived class or
• sub class or
• child class

The subclass inherits all the properties of the base class and saves time and effort.

Example idea:

• Person may contain name and age


• Student can inherit from Person
• Student adds roll number or marks

So Student automatically has the properties of Person.


1 TYPES OF INHERITANCE
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hybrid inheritance
• Hierarchical inheritance

These are different structures showing how classes are related.

The difference is in:

• how many base classes exist


• how many derived classes exist
• how inheritance paths connect

1.1 SINGLE INHERITANCE


This is the simplest type of inheritance and here one class is inherited by another class. It has one base class
one derived class

Diagram
employee
|
salary

It is the easiest inheritance type to understand and the most common starting point for learners.
1.1.1 SINGLE INHERITANCE EXAMPLE CODE

#include<iostream>
using namespace std;
#include<conio.h>

void add(int x, int y);


void add(float x, float y);

class employee {
protected:
int emp_no;
char name[20];

protected:
void get() {
cout << "enter the employee number:";
cin >> emp_no;
cout << "enter the employee name:";
cin >> name;
}
};

class salary: public employee


{
private:
float hra,basic_pay,pa,np;

public:
void accept() {
employee::get();
cout << "enter the basic pay:";
cin >> basic_pay;
cout << "enter hra(house rent allowance):";
cin >> hra;
cout << "enter pa (phone allowance):";
cin >> pa;
}

void calculate() {
np = basic_pay + pa + hra;
}

void display() {
cout << "Employment Number = " << emp_no << endl;
cout << "Name = " << name << endl;
cout << "Basic Pay = " << basic_pay << endl;
cout << "Housing Allowance = " << hra << endl;
cout << "Phone Allowance = " << pa << endl;
cout << "Net Pay = " << np << endl;
}
};

int main() {
salary s1;
[Link]();
[Link]();
[Link]();
return 0;
}

Here:

• employee is the base class


• salary is the derived class

The base class stores common employee details:

• employee number
• employee name

The derived class adds salary information:

• basic pay
• HRA
• PA
• net pay

The derived class can use inherited members because they are declared as protected.

This is important:

• protected means child classes can access them


• private would not allow direct access in the derived class

CODE OUTPUT

The sample output has entries like:

• employee number
• employee name
• basic pay
• HRA
• PA
• net pay
The program works in this order:

1. get employee details


2. get salary details
3. calculate total pay
4. display all values

Net pay formula used:

np = basic_pay + pa + hra

So this example teaches:

• inheritance
• access control with protected
• calling base class functions with scope resolution
1.2 MULTILEVEL INHERITANCE
When a class inherits a class which in turn inherits another class, it is called multilevel inheritance.

Diagram

student
|
marks
|
result

This means inheritance happens in levels.

Example:

• student contains student identity


• marks adds subject marks
• result computes total and average

This creates a chain.

1.2.1 MULTILEVEL INHERITANCE EXAMPLE CODE


#include<iostream>
using namespace std;

class student {
protected:
int rollnumber;
char name[20];

public:
void getstudent() {
cout << "enter roll number and name:";
cin >> rollnumber >> name;
}

void showstudent() {
cout << "roll number: " << rollnumber << endl;
cout << "Name of the student: " << name << endl;
}
};

class marks: public student


{
protected:
int p,c,e,m;

public:
void getmarks() {
student::getstudent();
cout << "Enter Physics, chemistry, English and maths marks:";
cin >> p >> c >> e >> m;
}

void showmarks() {
student::showstudent();
cout << "physics marks: " << p << endl;
cout << "chemistry marks: " << c << endl;
cout << "english marks: " << e << endl;
cout << "maths marks: " << m << endl;
}
};

class result: public marks


{
private:
float total,average;

public:
void getresults() {
marks::getmarks();
total = p + c + e + m;
average = total / 4;
}

void showresults() {
marks::showmarks();
cout << "total: " << total << endl;
cout << "percentage: " << average << endl;
}
};
int main() {
result c;
[Link]();
[Link]();
return 0;
}

This is a very good example of how information flows through multiple inheritance levels:

• student handles identity


• marks handles subjects
• result handles calculations

Notice that result can use p, c, e, and m because they are protected inside marks.

So data moves upward through the inheritance chain.

1.3 MULTIPLE INHERITANCE


If a class is derived from more than one base class, it is called multiple inheritance.

It is used when we need members of two or more classes having no direct connection between them.

All base classes are separated by commas.

Diagram

student science
\ /
\ /
\ /
result

In multiple inheritance:

• one class combines features from different base classes

This is useful when a class logically needs abilities from more than one source.
1.3.1 MULTIPLE INHERITANCE CODE

#include<iostream>
using namespace std;

class student {
protected:
int r;
char n[20];

public:
void getstudent() {
cout << "enter roll number and name:";
cin >> r >> n;
}

void showstudent() {
cout << "roll number:" << r << endl;
cout << "Name of the student: " << n << endl;
}
};

class science {
protected:
int p, c ;

public:
void getscience() {
cout << "Enter Physics and chemistry marks:";
cin >> p >> c;
}

void showscience() {
cout << "physics marks: " << p << endl;
cout << "chemistry marks: " << c << endl;
}
};

class result: public student, public science


{
private:
float total,average;

public:
void getresults() {
student::getstudent();
science::getscience();
total = p + c;
average = total / 2;
}

void showresults() {
student::showstudent();
science::showscience();
cout << "total: " << total << endl;
cout << "percentage: "<< average << endl;
}
};
int main() {
result c;
[Link]();
[Link]();
return 0;
}

Here:

• student stores roll number and name


• science stores science marks
• result combines both and calculates total and average

This shows how one class can inherit from two classes at the same time.

1.4 HIERARCHICAL INHERITANCE


When one class is inherited by two or more classes, it is called hierarchical inheritance.

Diagram

student
/ \
/ \
science commerce

In hierarchical inheritance:

• there is one common base class


• many derived classes use it

This is useful when several classes share common information.

Instead of repeating that information in each class, you place it once in the base class.
1.4.1 HIERARCHICAL INHERITANCE CODE

#include<iostream>
using namespace std;
class student {
protected:
int r;
char n[20];

public:
void getstud() {
cout << "enter roll number and name:";
cin >> r >> n;
}

void showstud() {
cout << "roll number: " << r << endl;
cout << "Name of the student: " << n << endl;
}
};

class science: public student {


private:
int p, c;

public:
void getscience() {
student::getstud();
cout << "Enter Physics and chemistry marks:";
cin >> p >> c;
}

void showscience() {
student::showstud();
cout << "physics marks: " << p << endl;
cout << "chemistry marks: " << c << endl;
}
};

class commerce: public student {


private:
int ac,st;

public:
void getcommerce() {
student::getstud();
cout << "Enter accounts and statistic marks:";
cin >> ac >> st;
}
void showcommerce() {
student::showstud();
cout << "accounts marks: " << ac << endl;
cout << "statistics marks: " << st << endl;
}
};

int main() {
science s;
commerce c;
[Link]();
[Link]();
[Link]();
[Link]();
return 0;
}

This example shows:

• science and commerce both inherit from student


• both get student details from the same base class

This is good design because student identity does not need to be repeated twice.

1.5 HYBRID INHERITANCE


Hybrid inheritance mixes more than one inheritance type in the same program. It can be a combination of
multiple inheritance and multilevel inheritance.

Diagram

A
|
B C
\ /
\ /
D

This combines:
• multilevel inheritance on one side
• multiple inheritance at the bottom

1.5.1 HYBRID INHERITANCE CODE

#include<iostream>
using namespace std;
class student {
protected:
int r;
char n[20];

public:
void getstud() {
cout << " Enter roll number and name:";
cin >> r >> n;
}

void showstud() {
cout << " Roll number:" << r << endl;
cout << " Name of the student: " << n << endl;
}
};

class science: public student {


protected:
int p, c;

public:
void getscience() {
student::getstud();
cout << " Enter Physics and chemistry marks:";
cin >> p >> c;
}

void showscience() {
student::showstud();
cout << " Physics marks: " << p << endl;
cout << " Chemistry marks: " << c << endl;
}
};

class commerce {
protected:
int ac, st;

public:
void getcommerce() {
cout << " Enter accounts and statistic marks:";
cin >> ac >> st;
}

void showcommerce() {
cout << " Accounts marks: " << ac << endl;
cout << " Statistics marks: " << st << endl;
}
};

class result: public science, public commerce {


private:
float total,average;

public:
void getresults() {
science::getscience();
commerce::getcommerce();
total = p + c + ac + st;
average = total/4;
}

void showresults() {
science::showscience();
commerce::showcommerce();
cout << " Total: " << total << endl;
cout << " Averagecentage: " << average << endl;
}
};

int main() {
result c;
[Link]();
[Link]();
return 0;
}

student
|
v
science commerce
\ /
\ /
\ /
result

The code above shows hybrid inheritance because it combines:

Multilevel inheritance: student → science → result


Multiple inheritance: result inherits from both science and commerce
So the total structure becomes hybrid as follows
2 VIRTUAL BASE CLASS
Problem diagram

A
/ \
B C
\ /
D

if:

• class B and class C inherit from class A


• class D inherits from both B and C

then class D may get two copies of class A members.

This is called the diamond problem.

Because there are two paths to A where an inherited class D may get duplicate A members, causing
ambiguity.

• D→B→A
• D→C→A

So ,

2.1 SOLUTION IS VIRTUAL BASE CLASS


To avoid duplication of A at D, the common base class A is made a virtual base class.

Then C++ ensures that only one copy of the base class is inherited, no matter how many paths exist.

This is the main purpose of the virtual keyword in inheritance:


• remove duplicate inheritance of a common base
• remove ambiguity
• ensure only one shared base class sub object exists

2.1.1 VIRTUAL BASE CLASS CODE

#include <iostream>
using namespace std;

class student {
protected:
int r;
char n[20];

public:
void getstud() {
cout << " Enter roll number and name:";
cin >> r >> n;
}

void showstud() {
cout << " Roll number: " << r << endl;
cout << " Name of the student: " << n << endl;
}
};

class science: public virtual student {


private:
int p, c;

public:
void getscience() {
cout << " Enter Physics and chemistry marks:";
cin >> p >> c;
}

void showscience() {
cout << " Physics marks: " << p << endl;
cout << " Chemistry marks: "<< c << endl;
}
};

class commerce: public virtual student {


private:
int ac,st;

public:
void getcommerce() {
cout << " Enter accounts and statistic marks:";
cin >> ac >> st;
}

void showcommerce() {
cout << " Accounts marks: " << ac << endl;
cout << " Statistics marks: " << st << endl;
}
};

class result: public science, public commerce {


public:
void getres() {
student::getstud();
science::getscience();
commerce::getcommerce();
}

void showres() {
student::showstud();
science::showscience();
commerce::showcommerce();
}
};

int main() {
result c;
[Link]();
[Link]();
return 0;
}

Notice:

class science: public virtual student


class commerce: public virtual student

This tells C++:

• both classes share the same student base


• do not duplicate it in result

That solves ambiguity.

You might also like