I read about virtual functions and found
VFs are used in inherited class polymorphism.
So, if a class and a derived class have the same function name, VF associates the corresponding function with the function call.
i.e. If the function in question is denoted as virtual in the base class, then the derived function of the class will be called. If it is not virtual, the base class function will be called.
In Java, by default: all functions are virtual C ++: not virtual and can be made virtual in Java using the final, private access modifier, but in C ++ using the virtual keyword to make the function virtual.
Based on the above theory, I wrote the code:
#include <iostream> class base{ public : virtual void function1(){ std::cout<<"BaseVirtual"<<std::endl; } void function2(){ std::cout<<"Base NonVirtual"<<std::endl; } }; class derieved: public base { public : void function1(){ std::cout<<"Derieved Virtual"<<std::endl; } void function2(){ std::cout<<"Derieved NonVirtual"<<std::endl; } }; int main() { base b1; derieved d1; b1.function1(); b1.function2(); d1.function1(); d1.function2(); }
Now, based on the fact, if its virtual function is called only by a derived function of the class, my output for the above program should be:
BaseVirtual Base NonVirtual Derieved Virtual Base NonVirtual
however, it turned out:
BaseVirtual Base NonVirtual Derieved Virtual Derieved NonVirtual
which should be right, of course. So my question is that the result completely violates the operator . If the function in question is assigned virtual in the base class, then the derived function of the class will be called. If it is not virtual, the base class function will be called. to call:
d1.function2();