Inheritance
is a fundamental concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and behaviors from another class. In C++, the concept of inheritance enables the creation of a new class (derived class or subclass) that incorporates the attributes and functionalities of an existing class (base class or superclass). This process promotes code reuse, extensibility, and the creation of a hierarchical class structure.
1. Single Inheritance:
A derived class inherits from only one base class.
class
Base
{
Copy Code
public:
void
baseFunction
() {
}
};
class
Derived
:
public
Base
{
public:
void
derivedFunction
() {
}
};
2. Multiple Inheritance:
A derived class inherits from more than one base class.
class
Base1
{
Copy Code
public:
void
base1Function
() {
}
};
class
Base2
{
public:
void
base2Function
() {
}
};
class
Derived
:
public
Base1
,
public
Base2
{
public:
void
derivedFunction
() {
}
};
3. Multilevel Inheritance:
A derived class is used as a base class for another class.
class
Grandparent
{
Copy Code
public:
void
grandparentFunction
() {
}
};
class
Parent
:
public
Grandparent
{
public:
void
parentFunction
() {
}
};
class
Child
:
public
Parent
{
public:
void
childFunction
() {
}
};
4. Hierarchical Inheritance:
Multiple derived classes inherit from a single base class.
class
Animal
{
Copy Code
public:
void
eat
() {
}
};
class
Dog
:
public
Animal
{
public:
void
bark
() {
}
};
class
Cat
:
public
Animal
{
public:
void
meow
() {
}
};
5. Hybrid Inheritance:
A combination of multiple inheritance types in a single program.
class
A
{
Copy Code
};
class
B
:
public
A
{
};
class
C
:
public
A
{
};
class
D
:
public
B
,
public
C
{
};
Some Basic Concepts of Inheritance:
(a). Base Class (Superclass):
The class whose properties and behaviors are inherited by another class.
(b).Derived Class (Subclass):
The class that inherits properties and behaviors from a base class.
(c). Protected Access Specifier:
Allows the derived class to access the protected members of the base class.
Public, Private, and Protected Inheritance: Determines the access level of the inherited members in the derived class.
Inheritance promotes code reusability, extensibility, and the creation of a hierarchical structure in the codebase. It establishes relationships between classes, reflecting the "is-a" relationship. Derived classes can reuse the functionality of base classes and, if needed, customize or extend that functionality.