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.
-
/*
-
* C++ Program to Demonstrate Multilevel Inheritance
-
* without Method overriding
-
*/
-
#include <iostream>
-
-
class Base {
-
int i;
-
public:
-
Base(int i = 0): i(i) { }
-
int val() const { return i; }
-
virtual ~Base() { }
-
};
-
-
class Derived : public Base
-
{
-
int i;
-
public:
-
Derived(int i = 0): i(i) { }
-
int val() const { return i; }
-
virtual ~Derived() {}
-
};
-
-
class MostDerived : public Derived
-
{
-
int i;
-
public:
-
MostDerived(int i = 0): i (i) { }
-
int val() const { return i; }
-
virtual ~MostDerived() { }
-
};
-
-
int main()
-
{
-
Base* B = new Base(1);
-
Base* D = new Derived(2);
-
Base* MD = new MostDerived(3);
-
-
std::cout << "Base.Value() = " << B->val() << std::endl;
-
std::cout << "Derived.Value() = " << D->val() << std::endl;
-
std::cout << "MostDerived.Value() = " << MD->val() << std::endl;
-
}
$ a.out Base.Value() = 1 Derived.Value() = 0 MostDerived.Value() = 0