Virtual function inheritance

烂漫一生 提交于 2019-12-05 01:41:56

You're correct.

I think that in this case the best solution is to try:

#include <iostream>

using namespace std;

class A {
   public:
      void print(){ cout << "print A" << endl; };
};

class B: public A {
    public:
       virtual void print(){ cout << "print B" << endl; };
};

class C: public B {
     public:
        void print(){ cout << "print C" << endl; };
};

int main()
{
   A *a = new C();
   B *b = new C();

   a->print(); // will print 'print A'
   b->print(); // will print 'print C'

   return 1;
}
theta

You are entirely correct. Child inherits what its ancestors have. Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called.

A is the base class for B,C,D. B is a the base class for C, D. and C is the base class for D too.

Of course you can do it. Virtual method is optional to override so it doesn't matter that you declare it in class A or B. If you dont want to use that method in class A then simply declare in in class B.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!