Polymorphism is the phenomenon that the same symbol or name has different interpretations in different situations. Polymorphism has two forms of expression:
- Compile-time polymorphism: The same object receives the same message but produces a different function call, typically implemented by a function overload, which implements the binding at compile time, which is a static binding.
- Runtime polymorphism: Different objects produce different actions when they receive the same message, and are usually implemented by virtual functions, which can only be implemented at run time, and are bound dynamically.
Virtual functions
A virtual function is a member function that is identified with the keyword in the base class and can be redefined in one or more derived classes. If a function is defined as a virtual function, even invoking the member function with a pointer to a base class object guarantees that the correct member function that is specific to the actual object is called. This is where the advantages of virtual functions lie.
Once the member function of the base class is defined as a virtual function, the derived class of the base class has the same member function (first name, return value type, number of arguments, and type) regardless of whether the keyword virtual is preceded or not, and it also has a virtual attribute, which is also a virtual function. Define the virtual function syntax format as follows:
Class < category name >
{
Virtual < return value type >< function name > (< formal parameter list >);
};
virtual function mechanism : If a virtual function is accessed through a reference or a pointer, it will not determine the specific calling function at compile time, and the corresponding function implementation is invoked only at runtime based on the specific object type. Note: The virtual function's "Dynamic bound virtual attribute" must be represented by the base class's pointer to the base class, and the virtual function cannot be dynamically bound through the object call.
"C + +" polymorphism (function overloading and virtual functions)