Module 6 - Inheritance
Module 6 - Inheritance
Inheritance
Inheritance - Types of Inheritance: Single inheritance, Multiple
Inheritance, Multi-level Inheritance, Hierarchical Inheritance -
Multipath Inheritance - Inheritance and constructors.
Inheritance
• It
allows us to create a new class (derived class) from an
existing class (base class).
• It provides reusability of code.
• Thederived class inherits the features from the base
class and can have additional features of its own.
• Inheritance is an is-a relationship. We use inheritance only
if an is-a relationship is present between the two classes.
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
Inheritance
class Animal {
// eat() function
// sleep() function
};
class Dog : public
Animal
{
// bark() function
};
Notice the use of the keyword public while inheriting Dog from Animal
// C++ program to demonstrate inheritance // derived class
class Dog : public Animal {
#include <iostream>
using namespace std; public:
void bark() {
// base class cout << "I can bark! Woof woof!!"
class Animal { << endl;
}
};
public: int main() {
void eat() { // Create object of the Dog class
cout << "I can eat!" << Dog dog1;
endl;
} // Calling members of the base class
dog1.eat();
dog1.sleep();
void sleep() {
cout << "I can sleep!" << // Calling member of the derived class
endl; dog1.bark();
}
return 0;
}; }
Types of Inheritance
Single inheritance
•A derived class inherits from a single base class
• The simplest type of inheritance
• For example, a dog inherits from an animal class
Syntax:
Multiple inheritance
A derived class inherits from more than one base class
Roll No: 25
Total marks: 120
Average marks: 40
Types of Inheritance
Multilevel inheritance
A class is derived from a class that is a
derived class
One class is used as a base class for another
class
class C is derived from Class B. Class B is in turn
derived from Class A.
#include <iostream> class Puppy:public Dog{
#include <string> public:
using namespace std; void weeping()
class Animal {
{ cout<<"Weeps!!";
string name=""; }
public: };
int tail=1; int main()
int legs=4; {
}; Puppy puppy;
class Dog : public Animal cout<<"Puppy has "<<puppy.legs<<"
{ legs"<<endl;
public: cout<<"Puppy has "<<puppy.tail<<"
void voiceAction() tail"<<endl;
{ cout<<"Puppy "; Output:
Puppy has 4 legs
cout<<"Barks!!!"; puppy.voiceAction(); Puppy has 1 tail
} cout<<" Puppy "; Puppy Barks!!!
}; puppy.weeping(); Puppy Weeps!!
Types of Inheritance
Hybrid inheritance
A combination of more than one type of inheritance
For example, a combination of multilevel and multiple
inheritances