[C ++] polymorphism (function overload and virtual function), polymorphism overload
Polymorphism means that the same symbol or name has different interpretations under different circumstances. There are two manifestations of polymorphism:
- Compile-time polymorphism: different function calls are generated when the same object receives the same message, which is generally implemented through function overloading. Binding is implemented during compilation and is a static binding.
- Runtime polymorphism: different objects produce different actions when they receive the same message. Generally, they are implemented through virtual functions. Binding can be implemented only at runtime and is a dynamic binding.
Virtual Functions
A virtual function is a member function identified by the keyword virtual in the base class. It can be redefined in one or more Derived classes. If a function is defined as a virtual function, the member function is called even by a pointer to the base class object, it can also ensure that the called member functions are correct and specific to the actual object. This is the advantage of virtual functions.
Once a member function of the base class is defined as a virtual function, the member function of the derived class of the base class has the same name (the name, return value type, number of parameters, and type are the same) no matter whether or not the keyword "virtual" is added, it also has a virtual function. Syntax format for defining virtual functions:
Class <class Name>
{
Virtual <return value type> <Function Name> (<parameter table> );
};
Virtual Function Mechanism: If you use a reference or pointer to access a virtual function, the system does not determine the specific function to be called during compilation. The corresponding function implementation is called only at runtime based on the specific object type. Note: The "dynamic binding virtual feature" of a virtual function must be reflected only when the base class pointer is used to reference the base class. The virtual function cannot be dynamically bound when it is called through an object.