I was reading this document about inheritance. https://www10.informatik.uni-erlangen.de/en/Teaching/Courses/SS2011/CPP/kellermann.pdf
There I read one line that
I want to know why we should not override non-virtual function?
I was reading this document about inheritance. https://www10.informatik.uni-erlangen.de/en/Teaching/Courses/SS2011/CPP/kellermann.pdf
There I read one line that
I want to know why we should not override non-virtual function?
#include <iostream>
class Base{
public:
void foo() const { std::cout << "Basic foo()" << std::endl; }
virtual void bar() const { std::cout << "Basic bar()" << std::endl; }
};
class Derived
: public Base
{
public:
void foo() const { std::cout << "Derived foo()" << std::endl; }
virtual void bar() const override { std::cout << "Derived bar()" << std::endl; }
};
int main(){
Derived obj;
Base& interface = obj;
interface.foo(); //"Basic foo()"
interface.bar(); //"Derived bar()"
}
Overriding non-virtual member may give unexpected results that are a pain to track. Even if you know what you're doing, you are usually not the only person working on a project and this sort of code is not idiomatic. Class hierarchies are usually used for dynamic polymorphism and when you override behavior of a polymorphic object, you expect it to behave accordingly when cast to base.
Just as every rule applying to C++ - it's more of a rule of thumb than a commandment, as this may occasionally be useful.