Users Online
· Guests Online: 77
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
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.
-
/*
-
* C++ Program to Illustrate Multilevel Inheritance
-
* with Method Overriding
-
*/
-
#include <iostream>
-
-
class Base {
-
int i;
-
public:
-
Base(int i = 0): i(i) { }
-
virtual int val() const { return i; }
-
virtual ~Base() { }
-
};
-
-
class Derived : public Base
-
{
-
int i;
-
public:
-
Derived(int i = 0): i(i) { }
-
virtual int val() const { return i; }
-
virtual ~Derived() { }
-
};
-
-
class MostDerived : public Derived
-
{
-
int i;
-
public:
-
MostDerived(int i = 0): i(i) { }
-
virtual 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() = 2 MostDerived.Value() = 3
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.