Question

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();
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top