INHERITANCE
DEFINITION:
Inheritance is one of the most useful and essential characteristics of object-oriented
programming.
The existing classes are main components of inheritance. The new classes are
created from existing one.
The properties of existing classes are simply extended to the new classes.
It promotes code reusability and establishes an is-a relationship between classes.
TYPES OF INHERITANCE:
Inheritance types are classified as follows:
1.Single Inheritance
2.Multiple Inheritance
3.Hierarchical Inheritance
4.Multilevel Inheritance
5.Hybrid Inheritance
6.Multi-path Inheritance
Single Inheritance:
Single inheritance is when a derived class inherits from only one base
class.
Example program:
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
void eat() {
cout << "Animal is eating." << endl;
}
};
// Derived class
class Dog : public Animal
{
public:
void bark()
{
cout << "Dog is barking." << endl;
}
};
int main()
{
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
return 0;
}
OUTPUT:
Animal is eating.
Dog is barking.
Explanation:
Animal is the base class with a method eat().
Dog is the derived class that inherits from Animal and adds its own
method bark()
The object d of type Dog can use both methods.