Inheritance is one of the most important concepts in Object-Oriented Programming. It allows us to define a new class (the Derived Class or Child Class) based on an existing class (the Base Class or Parent Class). This facilitates code reuse and establishes a logical "is-a" relationship between objects.
To inherit from a class, use a colon (:), followed by an access specifier (public, private, or protected), and then the name of the base class.
// Base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!" << endl;
}
};In this example, a Dog "is an" Animal. Because it inherits publicly, a Dog object can call both eat() (from the base class) and bark() (from the derived class).
C++ supports several models of inheritance, allowing for complex class hierarchies.
A derived class inherits from only one base class.
[ A ]
|
[ B ]A derived class inherits from more than one base class. This is a powerful feature of C++ but can lead to complexity (such as the "Diamond Problem").
[ A ] [ B ]
\ /
[ C ]class Car { /* ... */ };
class Boat { /* ... */ };
class AmphibiousVehicle : public Car, public Boat { /* ... */ };A derived class is created from another derived class.
[ A ]
|
[ B ]
|
[ C ]More than one derived class is created from a single base class.
[ A ]
/ \
[ B ] [ C ]A combination of more than one type of inheritance. For example, combining Hierarchical and Multiple inheritance.
When a class inherits from a base class, the access specifier determines how the inherited members are treated in the derived class:
public inheritance: public members of the base remain public in the derived class. protected members remain protected.protected inheritance: Both public and protected members of the base become protected in the derived class.private inheritance: Both public and protected members of the base become private in the derived class.Note: private members of the base class are never directly accessible from the derived class, regardless of the inheritance type.
public, protected, private) controls the visibility of inherited members.The process by which one class acquires the properties and methods of another class.
The class whose properties are inherited by another class.
The class that inherits properties from the base class.
C++ supports Single, Multiple, Multilevel, Hierarchical, and Hybrid inheritance.
Test your understanding with 3 questions
What is the main advantage of inheritance?
Which type of inheritance occurs when a derived class inherits from multiple base classes?
In C++, how do you specify that class B inherits publicly from class A?
2 Modules
2 Modules