Object Oriented Programming
Lecture
Types of Inheritance
Types of Inheritance
C++ supports six types of inheritance
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hybrid Inheritance
• Hierarchical Inheritance
• Multipath Inheritance
Single Inheritance
“A derived class with only one base class is
called single inheritance”
Class A
Class B
Inheritance (example)
#include <iostream> class Child : public Parent {
using namespace std;
};
class Parent{
public:
void myFunction()
{
cout << “Parent class“ << endl; int main() {
} Child myObj;
}; myObj.myFunction();
return 0;
}
Multilevel Inheritance
“A derived class with one base class and that base
class is a derived class of another is called
multilevel inheritance.”
Class A
Class B
Class C
Multilevel Inheritance
class Grand_Parent {
class Child : public Parent {
public: public:
void MyGrandParent() void Me()
{ {
cout << "Grand Parent class" << endl; cout << "Child class" << endl;
} }
}; };
class Parent : public Grand_Parent { int main() {
Child myObj;
public: myObj.MyGrandParent();
void MyParent() myObj.MyParent();
{ myObj.Me();
cout << "Parent class" << endl;
} return 0;
}; }
Multiple Inheritance
“A derived class with multiple base class is called
multiple inheritance.”
Class A Class B
Class C
Multiple Inheritance (example)
class MyClass { // Derived class
public: class MyChildClass : public MyClass, public MyOtherClass
void myFunction() { {
cout << “class 1“ << endl; };
}
};
// Another base class int main() {
class MyOtherClass { MyChildClass myObj;
public: myObj.myFunction();
void myOtherFunction() { myObj.myOtherFunction();
cout << “class 2" << endl; return 0;
} }
};
Hybrid Inheritance
“Inheritance in which the derivation of a class involves both
multilevel and multiple inheritance is called hybrid inheritance”
Class A
Class B Class C
Class D
Inheritance (example)
class C
class A
{
{
public:
public:
int y;
int x; int main()
C() {
}; {
y = 4;
} D obj1;
class B : public A obj1.sum();
};
{ return 0;
class D : public B, public C
public: }
{
B()
public:
{
void sum()
x = 10;
{
}
cout << "Sum= " << x + y;
};
}
};
Other types of Inheritance
Hierarchal Inheritance Multipath Inheritance
Thanks a lot