Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (child or derived class) to inherit properties and behaviors (methods) from another class (parent or base class). This promotes reusability and creates a hierarchical relationship between classes.
Key Characteristics of Inheritance
Characteristic
Description
Code Reusability
The derived class inherits properties and methods from the base class, reducing redundancy.
Extensibility
The child class can extend or override the functionality of the base class, adding or modifying behavior.
Hierarchical Structure
Inheritance establishes a parent-child relationship, forming a hierarchy among classes.
Method Overriding
A derived class can override the base class method to provide its own specific implementation.
Access to Base Class Members
The derived class can access public and protected members of the base class, but not private members.
Types of Inheritance
Type of Inheritance
Description
Single Inheritance
A class inherits from only one base class.
Multiple Inheritance
A class inherits from more than one base class (not supported by all languages, like Java).
Multilevel Inheritance
A class inherits from a base class, which is derived from another class, forming a chain of inheritance.
Hierarchical Inheritance
Multiple classes inherit from a single base class.
Hybrid Inheritance
A combination of two or more types of inheritance, such as multiple and multilevel inheritance.
Syntax for Inheritance in C++
Single Inheritance Example:
#include<iostream>// Base class (parent)classAnimal {
public:voideat() {
std::cout << "Eating..." << std::endl;
}
};
// Derived class (child)classDog : publicAnimal {
public:voidbark() {
std::cout << "Barking..." << std::endl;
}
};
intmain() {
Dog myDog;
myDog.eat(); // Inherited from Animal class
myDog.bark(); // Specific to Dog classreturn0;
}