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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.