简体   繁体   中英

Why Should not Override Non-Virtual Functions

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM