简体   繁体   中英

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? PS ->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;
}

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, eg test3->Test3::print();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM