Overriding a virtual function with a non-virtual function

I have a header file "testcode.h"

#ifndef TESTCODE_H #define TESTCODE_H class A { public: A(); ~A(); virtual void Foo(); public: int mPublic; protected: int mProtected; private: int mPrivate; }; class B : public A { public: B(); ~B(); void Foo(); }; #endif // TESTCODE_H 

and source file

 #include "TestCode.h" int main(int argc, char* argv[]) { A* b = new B(); b->Foo(); b->mPublic = 0; b->mProtected = 0; b->mPrivate = 0; delete b; return 0; } 

Here, I would like to know that when I call "b-> Foo", the function Foo of class B is called instead of class A. However, the function Foo of class B is not declared virtual. Can anyone clarify this?

+4
source share
2 answers

Once a function is declared virtual in the base class, it does not matter if the virtual keyword is used in the derived function of the class. It will always be virtual in derived classes (whether it is declared or not).

From the standard C ++ 11, 10.3.2:

If the vf virtual member function is declared in the Base class and in the Derived class obtained directly or indirectly from Base, the member is the vf function with the same name, list-type-list (8.3.5), cv-qualification and refqualifier (or lack of the same) as Base :: vf is declared, then Derived :: vf is also virtual (regardless of what is declared), and it overrides Base :: vf ....

+8
source

B::Foo does not need to be declared as virtual - the fact that A::Foo is virtual and B comes from A means that it is virtual (and overridden). Read the msdn article on virtual functions for more details.

+3
source

Source: https://habr.com/ru/post/1413865/


All Articles