The concept where a class can acquire properties and characteristics from a parent class is known as Inheritance. Inheritance stands out as a fundamental feature in C++ Object-Oriented Programming. It is possible to classify Inheritance based on the association between the derived class and the base class.
In C++, multilevel inheritance refers to a form of inheritance in which a class is inherited from another class that is already derived from a different class, thus forming a chain of inheritance. Each subsequent derived class inherits properties and behaviors from its immediate base class. This type of inheritance establishes a hierarchical relationship in a linear manner, for example, A -> B -> C. It enables method overriding, enabling derived classes to redefine functions that were inherited from their parent classes. Multilevel inheritance can be likened to the generational relationship among grandfather, father, and son.
Syntax
It has the following syntax:
class base_class {
... ... ...
};
class derived_class1 : access_specifier base_class {
... ... ...
};
class derived_class2 : access_specifier derived_class1 {
... ... ...
};
In this syntax,
- Base_class: It represents the base class of the program.
- Derived_class1: It is a class that inherits the properties and behaviour from the base class.
- Derivedclass2: It is a class that inherits the properties and behaviour from the derivedclass1, which creates a multilevel structure.
- Access_specifiers: These specifiers represent that the class is public, private, and protected.
Throughout multilevel inheritance, the visibility specifier between the derived and base classes holds significance in identifying which elements of the base class can be reached in the derived classes.
Block Diagram of Multilevel Inheritance
As depicted in the diagram above, class B acquires the attributes and functionality from class A, while class C inherits the attributes and behavior from class B.
Example for Multilevel Inheritance in C++
Let's consider a scenario to demonstrate the multilevel inheritance concept in the C++ programming language.
Example
#include <iostream>
using namespace std; //using standard namespace
class Appliance { //Base class
public:
void powerStatus() {
cout << "Appliance is turned on." << endl;
}
};
class WashingMachine : public Appliance { //derived class1
public:
void washClothes() {
cout << "Washing clothes..." << endl;
}
};
class SmartWashingMachine : public WashingMachine { //derived_class2
public:
void wifiControl() {
cout << "Smart control via WiFi enabled." << endl;
}
};
int main() { //Main Function
SmartWashingMachine sm;
sm.powerStatus();
sm.washClothes();
sm.wifiControl();
return 0;
}
Output:
Appliance is turned on.
Washing clothes...
Smart control via WiFi enabled.
Explanation
In this instance, we've utilized the base class Appliance. It contains a public method powerStatus which displays: "Appliance is turned on." Subsequently, the WashingMachine class derives from Appliance using public inheritance. The SmartWashingMachine class then derives from WashingMachine. Within the main function, we create an instance sm of the SmartWashingMachine type.
In function invocations, the sm.powerStatus triggers the function of the Appliance class. The sm.washClothes initiates the function of the WashingMachine class. The sm.wifiControl executes the method of the SmartWashingMachine class.
Multilevel Inheritance and Constructor in C++
A C++ constructor serves as a unique member function within a class that automatically triggers upon the creation of an object belonging to that class. Its primary purpose is to initialize the object's members.
Example
#include <iostream>
using namespace std; //using standard namespace
class Vehicle { //base class
public:
Vehicle() {
cout << "Vehicle constructor called." << endl;
}
void type() {
cout << "This is a vehicle." << endl;
}
};
class Car : public Vehicle { //intermediate derived class
public:
Car() {
cout << "Car constructor called." << endl;
}
void brand() {
cout << "Brand: Generic Car" << endl;
}
};
class ElectricCar : public Car { //derived class
public:
ElectricCar() {
cout << "ElectricCar constructor called." << endl;
}
void battery() {
cout << "Battery capacity: 80 kWh" << endl;
}
};
int main() { //Main Function
ElectricCar ecar;
ecar.type();
ecar.brand();
ecar.battery();
return 0;
}
Output:
Vehicle constructor called.
Car constructor called.
ElectricCar constructor called.
This is a vehicle.
Brand: Generic Car
Battery capacity: 80 kWh
Explanation
In this illustration, we are examining a foundational Vehicle class, containing a constructor and a method type for displaying a message. Each individual class includes its own constructor and member function. Upon instantiation of an ElectricCar object, constructors are invoked following the inheritance sequence (from Vehicle to ElectricCar), granting the ElectricCar object access to all inherited methods. This exemplifies the principles of reusability and hierarchy within the class structure.
Why do we use Multilevel Inheritance in C++?
In C++, utilizing inheritance enhances the reusability and readability of code. This mechanism allows derived classes to acquire the characteristics and functionalities of their parent classes. By doing so, it eliminates redundant code, thereby simplifying the complexity and enhancing the comprehensibility of the codebase.
Multilevel inheritance in C++ is employed to establish a class hierarchy, facilitating code reusability and structured organization of classes.
Multilevel Inheritance with Virtual Functions (Polymorphism)
Let's consider an example to demonstrate the multilevel inheritance with virtual methods in the C++ programming language.
Example
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Bark" << endl;
}
};
class Puppy : public Dog {
public:
void sound() override {
cout << "Puppy bark" << endl;
}
};
int main() {
Animal* a;
Puppy p;
a = &p;
a->sound();
return 0;
}
Output:
Puppy bark
Explanation
In this instance, a foundational class named Animal is defined, which includes a virtual function called sound. Following this, the class Dog inherits from Animal and redefines the sound function to display "Bark". Subsequently, the Puppy class further redefines the sound function to output "Puppy bark".
In the main function, a pointer of type Animal is set to reference a Puppy object. Upon invoking the a->sound method, the sound function of the Puppy class is executed, displaying the "Puppy bark" message. This scenario exemplifies dynamic polymorphism, where the executed function is determined by the specific object type during runtime.
Advantages of Multilevel Inheritance
Several advantages of Multilevel Inheritance in C++ are as follows:
- Code Reusability is the main advantage of multilevel inheritance in C++.
- When we obtain classes from other derived classes, we can more easily create a specialized class without having to write the code all over again.
- Multilevel inheritance also supports the Polymorphism and Modularity aspects of C++.
- It helps to improve code efficiency, structure, and flexibility.
Disadvantages of Multilevel Inheritance
Several disadvantages of Multilevel Inheritance in C++ are as follows:
- Increased Complexity: The hierarchy of classes becomes complex and hard to understand, particularly with numerous levels, which can result in difficulties in managing and maintaining the code.
- Tight Coupling: Derived classes become tightly coupled with their base classes, which makes it more difficult to change one without impacting the others, that decreases flexibility.
- Difficulty Debugging: Tracing bugs becomes harder due to several inheritance levels, which makes the process of debugging cumbersome and makes it more difficult to trace the problem source.
- Potential for Inheritance Anomalies: While less frequent in multilevel inheritance than in multiple inheritance, problems such as the "Diamond Problem" can still occur, which can result in ambiguity and method resolution conflicts.
Conclusion
In C++, multilevel inheritance represents a sophisticated idea in object-oriented programming, allowing a class to inherit properties from a derived class, thereby establishing a hierarchical inheritance structure. This approach promotes the reuse of code, enhances modularity, and supports polymorphism. Through the utilization of constructors and member functions, each tier within the hierarchy gains the ability to leverage the features of its parent and intervening classes, promoting effective and structured software development practices.
C++ Multilevel Inheritance MCQs
1) What is Multilevel Inheritance in C++?
- Inheriting multiple base classes into a single class
- Deriving a class from a base class and then using that derived class as a base class for another class
- Inheriting private members of a class
- Using multiple classes without inheritance
b) Creating a subclass from a superclass and subsequently utilizing that subclass as a superclass for another class
2) Which of the following classes acts as the intermediate class in this inheritance chain: Vehicle -> Car -> ElectricCar?
- Vehicle
- ElectricCar
- All of the above
3) Which concept is supported by multilevel inheritance along with code reuse in C++?
- Abstraction only
- Recursion
- Polymorphism and Modularity
- File Handling
4) Which of the following is an advantage of multilevel inheritance?
- Code reusability
- Slower execution
- Code duplication
- Reduced modularity
5) Which of the following keywords is used to define inheritance in C++?
- Class
- Inherits
- Extends
- : (Colon)