C++ Hierarchical Inheritance šŸŽÆ

beginner
14 min

C++ Hierarchical Inheritance šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into an exciting topic - Hierarchical Inheritance in C++. This concept is a powerful tool that helps organize code and reuse functionality. Let's get started!

Understanding Hierarchical Inheritance šŸ“

Hierarchical Inheritance is a type of inheritance where a class derives from multiple parent classes. It helps create a class hierarchy, where each class represents a category in a hierarchy.

Imagine a university, where every student belongs to a department. Each department may have different requirements, but a student shares common characteristics regardless of the department. Here, the student class can inherit from the department classes, thus creating a hierarchical relationship.

Creating Hierarchical Inheritance āœ…

Let's create a simple example of a Vehicle class with two derived classes Car and Bicycle. Both Car and Bicycle will inherit from the Vehicle class.

cpp
// Base class - Vehicle class Vehicle { public: std::string name; int wheels; Vehicle(std::string n, int w) : name(n), wheels(w) {} }; // Derived class - Car class Car : public Vehicle { public: int doors; Car(std::string n, int w, int d) : Vehicle(n, w) { doors = d; } }; // Derived class - Bicycle class Bicycle : public Vehicle { public: int gears; Bicycle(std::string n, int w, int g) : Vehicle(n, w) { gears = g; } };

In this example, we have a Vehicle class with two properties - name and wheels. The Car and Bicycle classes inherit from the Vehicle class and add their own properties - doors for Car and gears for Bicycle.

Using Hierarchical Inheritance šŸ’”

Now, let's see how to create and use instances of these classes.

cpp
int main() { Car myCar( "Tesla Model 3", 4, 4 ); Bicycle myBicycle( "Trek", 2, 21 ); std::cout << "My Car: " << myCar.name << " has " << myCar.wheels << " wheels and " << myCar.doors << " doors." << std::endl; std::cout << "My Bicycle: " << myBicycle.name << " has " << myBicycle.wheels << " wheels and " << myBicycle.gears << " gears." << std::endl; return 0; }

In the main function, we create instances of Car and Bicycle classes, and print their properties.

Quiz šŸŽ“

Quick Quiz
Question 1 of 1

Which of the following statements describes the relationship between the `Car` and `Bicycle` classes in the example?

That's it for today! We hope you found this lesson on C++ Hierarchical Inheritance helpful. In the next lesson, we'll dive deeper into inheritance and explore more advanced concepts. Stay tuned! šŸŽÆ