Module6 Lect1,2,3,4,5,6
Module6 Lect1,2,3,4,5,6
Inheritance
• Inheritance is a fundamental object-oriented design technique used to create and organize
reusable classes.
• Inheritance is the ability of one class to inherit the properties of another class.
• A new class can be created from an existing class.
• The existing class is called BASE CLASS or SUPER CLASS and the new class is called DERIVED CLASS
or SUB CLASS.
• As the name implies, the child inherits characteristics of the parent
• Child inherits the methods and data defined by the parent class
• We can refer to these inherited methods and variables as if they were declared locally in the class
• Example:
• Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled
triangular arrowhead pointing to the parent class
• Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the
parent
Why and when to use inheritance?
Vehicle
Car Bicycle
2-door 4-door
Advantages of inheritance
• When a class inherits from another class, there are three benefits:
(1) You can reuse the methods and data of the existing class
(2) You can extend the existing class by adding new data and new
methods
(3) You can modify the existing class by overloading its methods
with your own implementations
Inheritance is the property that allows the
reuse of an existing class to build a new class
Private Yes No No
Inheritance
Person
Employee
Syntax of single inheritance in C++
class Base_Class
{
// class definition
};
class Derived_Class: visibility mode Base_Class_name
{
// body of the derived class
};
int main()
{
Base_Class obj1;
Derived_Class obj2;
// code
}
Example for Single Inheritance
# include <iostream> int main()
using namespace std; {
class B
D n;
{
public: n.x=100;
int x; n.y=200;
}; cout<<"\n x="<<n.x;
class D: public B cout<<"\n y=" <<n.y;
{ n.disp();
public: }
int y;
void disp()
{
cout<<"\n access base members:"<<x;
}
};
Modes of inheritance in C++
Public mode:
• In the public mode of inheritance, when a child class is derived from the
base or parent class, then the public member of the base class or parent
class will become public in the child class also, in the same way, the
protected member of the base class becomes protected in the child class,
and private members of the base class are not accessible in the derived
class.
Protected mode:
• In protected mode, when a child class is derived from a base class or
parent class, then both public and protected members of the base class will
become protected in the derived class, and private members of the base
class are again not accessible in the derived class. In contrast, protected
members can be easily accessed in the derived class.
Modes of inheritance in C++
Private mode
In private mode, when a child class is derived from a base class, then
both public and protected members of the base class will become
private in the derived class, and private members of the base class are
again not accessible in the derived class.
Modes of inheritance
class A
{
public:
int x; class C : protected A
{
protected: // x is protected
int y; // y is protected
// z is not accessible from C
private: };
int z;
}; class D : private A // 'private' is default for classes
{
// x is private
class B : public A // y is private
// z is not accessible from D
{
};
// x is public
// y is protected
// z is not accessible from B
};
# include <iostream> int main()
using namespace std; {
class B D n;
{ n.x=100;
public: n.y=200;
int x; cout<<"\n x="<<n.x;
}; cout<<"\n y=" <<n.y;
n.disp();
class D: private B }
{
public:
int y;
void disp()
{
cout<<"\n access base members:"<<x;
}
};
Example for Single Inheritance
# include <iostream> class D: public B
using namespace std; {
class B public:
{ int y;
private:
int x; D()
public: {
B() y=200;
{ }
x=100; void disp()
} {
void show() cout<<"\n derived class members:"<<y; }
{ };
cout<<"\n access base members:"<<x; int main()
} {
}; D n;
n.show();
n.disp();
}
Employee processing using single Inheritance
#include<iostream.h> class salary : public emp {
#include<conio.h> float bp, hra, da, pf, np;
public:
class emp { void get1() {
public: cout << "Enter the basic pay:";
cin>>bp;
int eno; cout << "Enter the Humen Resource Allowance:";
char name[20], des[20]; cin>>hra;
cout << "Enter the Dearness Allowance :";
void get() { cin>>da;
cout << "Enter the Profitablity Fund:";
cout << "Enter the employee number:"; cin>>pf;
cin>>eno; }
cout << "Enter the employee name:";
void calculate() {
cin>>name; np = bp + hra + da - pf;
cout << "Enter the designation:"; }
cin>>des;
} void display() {
cout << eno << "\t" << name << "\t" << des <<
}; "\t" << bp << "\t" << hra << "\t" << da << "\t" << pf <<
"\t" << np << "\n";
} };
Continuation of Previous Program
void main() {
int i, n;
char ch;
salary s[10];
cout << "Enter the number of employee:";
cin>>n;
for (i = 0; i < n; i++) {
s[i].get();
s[i].get1();
s[i].calculate();
}
cout << "\ne_no \t e_name\t des \t bp \t
hra \t da \t pf \t np \n";
for (i = 0; i < n; i++) {
s[i].display();
}
}
Multilevel Inheritance
A derived class is created from another derived class.
Vehicle Person
Car Employee
Teacher
class C : public A,public B
#include <iostream>
using namespace std; { int main()
class A {
public: C c;
{
protected: void display() c.get_a(10);
int a; c.get_b(20);
{ c.display();
public:
void get_a(int n) cout << "The value of a is : " <<a<<endl;
{ return 0;
cout << "The value of b is : " <<b<<endl;
a = n; }
} cout<<"Addition of a and b is : "<<a+b;
}; }
class B
};
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
#include<iostream> class statement : public student, public sports
using namespace std; {
int tot, avg;
public:
class student {
protected: void display() {
int rno, m1, m2; tot = (m1 + m2 + sm);
public: avg = tot / 3;
cout << "\n\n\tRoll No : " << rno << "\n\tTotal : " <<
void get() { tot;
cout << "Enter the Roll no :"; cout << "\n\tAverage : " << avg;
cin>>rno; }
cout << "Enter the two marks :"; };
cin >> m1>>m2;
}
}; int main()
{
class sports statement obj;
{ obj.get();
protected: obj.getsm();
int sm; // sm = Sports mark obj.display();
public: return 0;
void getsm() { }
cout << "\nEnter the sports mark :";
cin>>sm;
}
};
Hierarchical Inheritance
If more than one class is inherited from a base class, it's known as hierarchical
inheritance. In general, all features that are common in child classes are included
in base class in hierarchical inheritance.
Employee
Permanent Temporary
Employee Employee
For example, Physics, Chemistry, Biology are derived from Science class. Similarly, Dog, Cat, Horse are derived
from Animal class.
Syntax of Hierarchical Inheritance
class base_class
{
... .. ...
}
class Racing
{
public:
Racing()
{
cout<<"\n this is a Racing class-intermediate baseclass2";
}
};
How to call a parent class function from derived class function in C++?
#include <iostream> int main() {
using namespace std;
class p1 d1 d;
{
public: d.first();
void first()
{ return 0;
cout << "\nThe parent class p1 function is called.";
} }
};
class d1 : public p1
{
public:
void first()
{
cout << "The derived class d1 function is called.";
p1::first();
}
};
Multi-Path Inheritance
• When a class inherits the properties of another class two or more times through two or more
different paths it is known as multipath inheritance.
• When a class is derived from two base classes and those two base classes have one common
base class is called multipath inheritance
• The diamond problem occurs when two superclasses of a class have a common base class.
• To avoid this ambiguity scope resolution operator is used.
• The properties are inherited more than once, so more memory is consumed and ambiguity
(doubt) gets created, in order to avoid this extra consumption of memory and ambiguity, we
declare the base class as virtual while giving the definition of the derived class.
To avoid the ambiguity problem
#include<iostream> Ex: MULTIPATH Inheritance
class ClassA { int main()
public: {
int a; ClassD obj;
}; // obj.a = 10; // Statement 1, Error [ambiguous]
// obj.a = 100; // Statement 2, Error [ambiguous]
class ClassB : public ClassA {
public: obj.ClassB::a = 10; // Statement 3 OUTPUT
int b; obj.ClassC::a = 100; // Statement 4 a from ClassB : 10
}; a from ClassC : 100
obj.b = 20; b : 20
class ClassC : public ClassA { obj.c = 30; c : 30
public: obj.d = 40; d : 40
int c; cout << " a from ClassB : " << obj.ClassB::a;
}; cout << "\n a from ClassC : " << obj.ClassC::a;
class ClassD : public ClassB, public ClassC cout << "\n b : " << obj.b;
{ cout << "\n c : " << obj.c;
public: cout << "\n d : " << obj.d << '\n';
int d; }
};
VIRTUAL BASE CLASS
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.
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
using namespace std;
class A { NOTE :
public: • In C++, you can use virtual inheritance to resolve ambiguity in
int a; inheritance. Virtual inheritance is a way of specifying that a class
A() // constructor should be inherited virtually,
{
a = 10;
} • virtual can be written before or after the public. Now only one
}; copy of data/function member will be copied to class C and class B
class B : public virtual A and class A becomes the virtual base class.
{ • The virtual base class is a concept used in multiple inheritances to
}; prevent ambiguity between multiple instances.
class C : public virtual A
{ • On declaring the base class as virtual the properties of the base
};
class are inherited only once and hence no extra memory is
class D : public B, public C
{ consumed and the problem of ambiguity automatically gets
}; solved.
int main()
{ • The class A has just one data member a which is public. This class
D object; // object creation of class d is virtually inherited in class B and class C. Now class B and class C
cout << "a = " << object.a << endl; becomes virtual base class and no duplication of data member a is
return 0; done.
}
#include <iostream>
using namespace std; int main()
{
class A { D object;
public: object.show();
void show() }
{
cout << "Hello from A \n";
}
};
Output:
class B : public virtual A { Hello from A
};
Base class constructors are always called in the derived class constructors.
Whenever you create derived class object, first the base class default
constructor is executed and then the derived class's constructor finishes
execution.
Points to Remember
1.Whether derived class's default constructor is called or parameterised is
called, base class's default constructor is always called inside them.