Inheritance is a feature in object-oriented programming that allows new classes to be created from existing classes. The new class created is called the "derived class" or "child class," and the existing class is known as the "base class" or "parent class". In C++, inheritance is implemented using the syntax class DerivedClass : accessSpecifier BaseClass
. The access specifier can be public
, protected
, or private
, and determines how the derived class can access the members of the base class.
In C, inheritance can be achieved by maintaining a reference to the base class object in the derived class object. The canonical way to represent something like inheritance in C is to simply put a struct of the "superclass" as the first element. To get the "base," you can access that element directly, or up-cast the struct. However, this approach does not deal with polymorphism or dynamic dispatch.
There are different types of inheritance in C++, including:
- Single Inheritance: A derived class inherits from a single base class.
- Multiple Inheritance: A derived class inherits from multiple base classes.
- Multilevel Inheritance: A derived class is created from another derived class.
- Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
- Hybrid Inheritance: A combination of multiple inheritance and multilevel inheritance.
Inheritance allows for code reuse and helps in the logical and hierarchical organization of code.