2

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 enter image description here

I want to know why we should not override non-virtual function?

Asif Mushtaq
  • 3,658
  • 4
  • 44
  • 80
  • 3
    I disagree. this is may be a recomendation , but not obligation. declaring a function virtual when overriding it may prevent the "parent pointer - child object" problem in the future (and saving you some time debugging the code), but this is not an obligation. if you don't plan on using polymorhpism on derived class, there is no obligation declare the function virtual. remeber, the privilege to not declare a function virtual is *by design*, as opposed to , e.g. Java and C#. – David Haim Jun 06 '15 at 07:06
  • There is a better answer to this question than on this thread here : https://stackoverflow.com/a/62622149/6547518 –  Aug 23 '21 at 09:14

1 Answers1

2
#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.

tsuki
  • 907
  • 4
  • 17
  • OP: but it is *not* wrong, just different behaviour which is not what people might expect – deviantfan Jun 06 '15 at 07:02
  • 1
    @deviantfan I don't understand why it is not wrong since it is not correct regarding the "override specifier" definition : https://en.cppreference.com/w/cpp/language/override . –  Aug 23 '21 at 09:10