1 //For a derived class to override a base class member function, the object that invokes the member function is determined at the time of the program's compilation, that is, either a base class object or a derived class object, which can only be a fixed one and cannot be changed while the program is operating2 //However, for virtual functions, the object that invokes the member function is determined when the program is run, depending on whether the object the object pointer is currently pointing to is a base class object or a derived class object, to determine the current3 //The member function that is called is a member function of a base class or a member function of a derived class4 //Here is an example5#include <iostream.h>6 7 classa{8 Public:9 A () {}Ten~A () {} One Virtual voidF1 ()Const{ Acout<<"base class member function F1 ()"<<Endl; - } - voidF2 ()Const{ thecout<<"base class member function F2 ()"<<Endl; - } - }; - + classB: Publica{ - Public: + B () {} A~B () {} at Virtual voidF1 ()Const{ -cout<<"derived class member function F1 ()"<<Endl; - } - voidF2 ()Const{ -cout<<"derived class member function F2 ()"<<Endl; - } in }; - to intMain () { +APA; - the A MyA; * B MyB; $ Panax Notoginsengpa=&MyA; -Pa->F1 (); thePa->F2 (); + Apa=&MyB; thePa->F1 (); +Pa->F2 (); - $ $ return 0; -}
C + + Learning (23)