Users Online

· Guests Online: 40

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Multilevel Inheritance with Overriding in C++

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.83 seconds
10,272,926 unique visits