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
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Apply for Information Technology Internship
- Buy Programming Books
- Buy Computer Science Books