Inheritance allows us to define a class in terms of another class, and it makes easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. If a class is derived from another derived class then it is called multilevel inheritance. In other terms, multilevel inheritance method is using a class which has more than one parent class. Multilevel Inheritance differences from the Multiple Inheritance because of it has a previous class in each levels of new class definitions.
Here is a multilevel inheritance example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class base_class_name // base class { // base properties and functions }; class class_name1 : <acessspecifier> base_class_name // derived class from base_class_name { // properties and functions }; class class_name2 : <accessspecifier> class_name1 // derived from derived class class_name1 { // properties and functions }; |
For example, if we take lives as a base class then animals are the derived class which has features of animals and then mammals are the also derived class that is derived from sub-class animal which inherit all the features of lives.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class lives // base class { // base properties and functions }; class animals : public lives // derived from lives { // properties and functions }; class mammals : public animals // derived from derived class animals { // properties and functions }; |
From this example, we prepared a Multilevel Inheritance example below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include <iostream> class lives //single base class { public: int weight; void set_weight(int w) { weight = w; } }; class animals : public lives // derived class from base class { public: int type; // 0:Sea 1:Ground 2:Air Animal void set_type(int t) { type = t; } }; class mammals : public animals // derived from class derive1 { private: int num_of_legs; public: void set_numoflegs(int l) { num_of_legs=l; } void info() { std::cout << "Weight:" << weight << '\n'; std::cout << "Type:" << type << '\n'; std::cout << "Number of Legs:" << num_of_legs << '\n'; } }; int main() { mammals elephant; elephant.set_weight(5000); elephant.set_type(1); // 0:Sea 1:Ground 2:Air Animal elephant.set_numoflegs(4); elephant.info(); getchar(); return 0; } |
Here all lives has weight, and animals has a type value and mammals has number of legs. We define an elephant object as a mammal, and we are able to reach all properties and methods of mammals, animals derived classes and lives base class.
Get started building powerful apps with C++Builder!
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition