Multilevel Inheritance with Overriding in C++

This C++ program demonstrates multilevel inheritance with method overriding in classes. The val() methods have been declared virtual, the V-table always keeps track of the latest version of val() method. As the pointer to an object is upcast to a ‘less-derived’ Class, correct version of the method is called when a particular method val() is called as the V-table now keeps track of the latest version of method 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 Illustrate Multilevel Inheritance
  3.  * with Method Overriding
  4.  */
  5. #include <iostream>
  6.  
  7. class Base {
  8.     int i;
  9.     public:
  10.         Base(int i = 0): i(i) { }
  11.         virtual 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.         virtual 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.         virtual 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() = 2
MostDerived.Value() = 3

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

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

If you find any mistake above, kindly email to [email protected]

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.