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

2

2

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();
}
Hereabouts answered 18/12, 2013 at 6:13 Comment(1)
yes but it may be clearer to have virtual in inherited classes as well even if it is not, strictly speaking, needed.Nascent
C
3

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.

Conquistador answered 18/12, 2013 at 8:17 Comment(0)
W
3

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.

Ween answered 18/12, 2013 at 6:19 Comment(0)
C
3

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.

Conquistador answered 18/12, 2013 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.