One of the most important features in C + + is that multiple states use the same name function to implement different functions, polymorphism is divided into multi-state at compile time and runtime polymorphism, while compile-time polymorphism mainly refers to operator overloading and function overloading, while runtime polymorphism refers to polymorphism of derived classes and virtual functions. Even if an application or pointer to a base class can refer to a method in a derived class (you cannot refer to a new method in a derived class that does not have a base class), a pointer or reference to a derived class will call the method in the base class directly if it is not indicated to be a virtual function. This is because if defined as a virtual function, a virtual function table will be added to the object to hold the virtual function address, and if the derived class redefined the virtual function, the virtual function address will be changed, and the address will change to a method in the derived class.
For example:
#include "stdio.h" #include <iostream>using namespace Std;class a{private:char *name;public: A (char *str); A (); void Show (); Char *getname ();}; A::a () {}a::a (char *str) {name=str;} void A::show () {cout<< "My name is" <<name<< "\ n";} Char *a::getname () {return name;} Class Singer:public A{public:singer (char *str); void sing (); void Show ();}; Singer::singer (char *str): A (str) {}void singer::sing () {cout<< "I Can sing" << "\ n";} void Singer::show () {cout<< "My Name is" <<getname () << "\ n";cout<< "I Can sing" << "\ n";} int main () {a * a1= new Singer ("Xxz"); A1->show ();//A reference or pointer to a base class can refer to a member of a base class in a derived class GetChar (); return 0;}
The Show method in the base class is not set to a virtual function, the show of the base class is called directly
Run the result as
If you add virtual in front of show, the base class will call methods of the derived class
Run the result as
Added: 1 constructors cannot be virtual functions, constructors cannot be overloaded
2 copy constructors and operators cannot be virtual functions
3 destructors should be virtual, destroying derived classes should call the destructor of the derived class, not the destructor of the base class
Parsing virtual functions in C + +