<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > recently wrote the program found that the base class function of a derived class object if the base class virtual function is called, it will call the corresponding function of the derived class, not the corresponding function of the base class I want to call. </span>
Here is an example to illustrate:
Base class Base{public:void Funa (); virtual void Funb ();p rotected:private:};void Base::funa () {cout<< " This is the base class Funa () "<<endl;funb ();} void Base::funb () {cout<< "This is the Base class Funb ()" <<ENDL;} Derived classes class Derivate:p ublic base{public:virtual void Funb ();p rotected:private:};void Derivate::funb () {cout<< " This is the Derivate class Funb () "<<ENDL;}
I have created a base class base and a derived class derivate, where the base class has a function Funa () and a virtual function Funb (). In a derived class, I override the function Funb ().
In Base::funa () I called FUNB (), then I want to call Base::funb (). Now let's try to write a test:
void Main () {cout<< "1, calling the derived class object's Funa ():" <<endl;derivate Tmp;tmp.funa ();cout<< "2, Call the base class pointer to the Funa () of the derived class object: "<<endl; base* pbase;pbase = &tmp;pbase->funa ();}
The operating result is:
Actually if I call Funa () with a derived class object, then he will call Derivate::funb () instead of Base::funb (), and the result of running fun () is the same as when the base-class pointer points to the derived class object.
Workaround: So both want to maintain the FUNB () function polymorphism, but also in the base class can be called exactly the base class function Base::funb () should be how to do? Then add the class qualifier:
void Base::funa () {cout<< "This is the Base class Funa ()" <<endl; Base::funb ();}
therefore, when a base class function calls a virtual function, be aware of the addition of the class qualifier.
All test code:
#include <iostream>using namespace std;//base class Base{public:void Funa (); virtual void Funb ();p rotected:private: };void Base::funa () {cout<< "This is the Base class Funa ()" <<endl;funb ();} void Base::funb () {cout<< "This is the Base class Funb ()" <<ENDL;} Derived classes class Derivate:p ublic base{public:virtual void Funb ();p rotected:private:};void Derivate::funb () {cout<< " This is the Derivate class Funb () "<<ENDL;} void Main () {cout<< "1, calling the derived class object's Funa ():" <<endl;derivate Tmp;tmp.funa ();cout<< "2, Call the base class pointer to the Funa () of the derived class object: "<<endl; base* pbase;pbase = &tmp;pbase->funa ();}
The pitfall of C + + virtual function--the base class function of derived class object called base class virtual function error