Define the method once to be virtual in the inheritance hierarchy to make polymorphism to work

限于喜欢 提交于 2019-12-24 01:25:45

问题


Is it sufficient to define the method once to be virtual in the inheritance hierarchy to make polymorphism to work. In the following example Der::f is not defined to be virtual but d2->f(); prints der2 I am using VS IDE (may be it is only there...)

class Base
{
public:
    virtual void f() { std::cout << "base"; }
};
class Der : public Base
{
public:
    void f() { std::cout << "der"; } //should be virtual?
};
class Der2 : public Der
{
public:
    void f() { std::cout << "der2"; }
};

int main()
{
    Der* d2 = new Der2();
    d2->f();
}

回答1:


Yes, polymorphism will work if you define method as a virtual only in your Base class. However, it is a convention I came across working with some large projects to always repeat virtual keyword in method declarations in derived classes. It may be useful when you are working with a lot of files with complex class hierarchy (many inheritance levels), where classes are declared in separate files. That way you don't have to check which method is virtual by looking for base class declaration while adding another derived class.




回答2:


Everything that inherits from Base - directly or through several layers will have f() virtual as if the class declarion had explicitely placed virtual when f() was declared.



来源:https://stackoverflow.com/questions/20650875/define-the-method-once-to-be-virtual-in-the-inheritance-hierarchy-to-make-polymo

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