Multilevel Inheritance without Overriding in C++
Posted by Superadmin on August 08 2022 09:35:28

 

 

Multilevel Inheritance without Overriding in C++

This C++ program demonstrates multilevel inheritance without method overriding in classes. The method val() has not been overridden in the multilevel inherited classes. The val() methods have not been declared virtual, so the V-table doesn’t keep track of the latest version of val() method. Rather uses method val() specified in the Base Class when called by a pointer to Base Class. The run-time type-identification doesn’t happen and the compiler calls Base::val().

 

Here is the source code of the C++ program demonstrates multilevel inheritance without method overriding in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate Multilevel Inheritance
  3.  * without Method overriding
  4.  */
  5. #include <iostream>
  6.  
  7. class Base {
  8.     int i;
  9.     public:
  10.         Base(int i = 0): i(i) { }
  11.         int val() const { return i; }
  12.         virtual ~Base() { }
  13. };
  14.  
  15. class Derived : public Base
  16. {
  17.     int i;
  18.     public:
  19.         Derived(int i = 0): i(i) { }
  20.         int val() const { return i; }
  21.         virtual ~Derived() {}
  22. };
  23.  
  24. class MostDerived : public Derived 
  25. {
  26.     int i;
  27.     public:
  28.         MostDerived(int i = 0): i (i) { }
  29.         int val() const { return i; }
  30.         virtual ~MostDerived() { }
  31. };
  32.  
  33. int main()
  34. {
  35.     Base* B = new Base(1);
  36.     Base* D = new Derived(2);
  37.     Base* MD = new MostDerived(3);
  38.  
  39.     std::cout << "Base.Value() = " << B->val() << std::endl;
  40.     std::cout << "Derived.Value() = " << D->val() << std::endl;
  41.     std::cout << "MostDerived.Value() = " << MD->val() << std::endl;
  42. }

 

$ a.out
Base.Value() = 1
Derived.Value() = 0
MostDerived.Value() = 0