Neerav Bohra Neerav Bohra - 1 year ago 26
C++ Question

Polymorphism in multilevel inheritance

The derived class Test2 and Test3 in below code are not virtual type then why are the functions overridden and how to stop that from happening?
P.S ->I am a newbie so the question might be stupid sorry for that.

#include <iostream>
using namespace std;

class Test {
public:
int a, b, c;
Test(int x, int y, int z) {
a = x;
b = y;
c = z;
}
void print() { cout << "a= " << a << "b= " << b << "c= " << c << endl; }
};

class Test2 : public Test {
public:
int d, e;
Test2(int a, int b, int c, int x, int y) : Test(a, b, c) {
d = x;
e = y;
}
virtual void print() { cout << "d= " << d << "e= " << e << endl; }
};

class Test3 : public Test2 {
public:
int f;
Test3(int a, int b, int c, int d, int e, int x) : Test2(a, b, c, d, e) {
f = x;
}
void print() { cout << "f= " << f << endl; }
};

class Test4 : public Test3 {
public:
int g;
Test4(int a, int b, int c, int d, int e, int f, int x)
: Test3(a, b, c, d, e, f) {
g = x;
}
void print() { cout << "g= " << g << endl; }
};

int main() {
Test *test;
Test2 *test2;
Test3 *test3;
Test4 test4(1, 2, 3, 4, 5, 6, 7);
test = &test4;
test2 = &test4;
test3 = &test4;
test->print();
test2->print();
test3->print();
test4.print();
return 0;
}

Answer Source

Test2::print is virtual and therefore a call to print on a pointer to Test2 or a pointer to a class that derives from Test2 will use the runtime type of the object to determine which function to call. In your case the runtime type of the object is Test4 so it will call Test4::print. That is the point of virtual functions.

If you want to explicitly call a different version of print you can do so, e.g test3->Test3::print();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download