As long as the base class has declared the Virtue keyword when defining a member function, when overridden by a derived class, the Virtue keyword can be added without affecting the implementation of the polymorphic.
Easy to confuse with hiding:
Shadowing refers to a function of a derived class that masks a base class function with the same name as the following rule:
1) If the function of the derived class has the same name as the function of the base class, but the parameters are different. At this point, the function of the base class is hidden, regardless of the virtual keyword (Note that it is not confused with overloading).
2) If the function of the derived class has the same name as the function of the base class, and the parameters are the same, the base class function does not have the virtual keyword. At this point, the functions of the base class are hidden (note the difference between this and the function overloading, where overloading occurs in the same class.) )。
#include <iostream>using namespace Std;class base{public:virtual void F (float x) {cout<< "Base::f" <<x ;} virtual void G (float x) {cout<< "Base::g" <<X;} void h (float x) {cout<< "Base::h" <<x;}}; Class Driver:public base{public:void F (float x) {cout<< "D::f" <<X;} virtual void g (int x) {cout<< "D::g" <<X;} void h (float x) {cout<< "D::h" <<x;}}; int main (int argc, char const *argv[]) {Driver D; base* pb=&d;driver* pd=&d;pd->f (1.2f);p b->f (1.2f);pd->g (1.2f);p b->g (1.2f);pd->h (1.2f);p B- >h (1.2f); return 0;}
Please note that the F () function is covered, while g () and H () are hidden. From the running results above, we can notice that when the function f () is called with the base class pointer and the derived class pointer in the overlay, the system executes the derived class function f (), not the base class F (). In the hidden mode, the function g () is called with the base class pointer and the derived class pointer, H (), the system will differentiate, when the base class pointer is called, the system executes the base class G (), H (), and when the derived class pointer is called, the system "hides" the base class F (), executes the derived class F (), which is the origin of "hiding".
function hiding in C + +