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

Is it enough to define a method once to be virtual in the inheritance hierarchy to make polymorphism work. In the following example, Der :: f is not defined as virtual , but d2->f(); prints der2 I'm using VS IDE (maybe it's 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(); } 
+2
c ++ polymorphism virtual-functions
source share
2 answers

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

+3
source share

Anything that inherits from Base, either directly or across multiple layers, will have f () virtual, as if the class declaration was explicitly placed virtual when f () was declared.

+3
source share

All Articles