C++: Virtual functions and polymorphism

The only use of virtual functions in C++ is to form polymorphism.

The purpose of providing polymorphism in C++ is to provide "all-round" access to member variables and member functions of all derived classes (including direct derivation and indirect derivation) through base class pointers, especially member functions. Without polymorphism, we can only access member variables.

 

Only the virtual function of the derived class shadows the virtual function of the base class (the function prototype is the same) to constitute polymorphism.

Constructors cannot be virtual functions. Destructors can be declared virtual, and sometimes they must be declared virtual. A derived class destructor always calls the base class's destructor

The following are the conditions that constitute polymorphism:

    • There must be an inheritance relationship;
    • There must be virtual functions of the same name in an inheritance relationship, and they are shadowing (overriding) relationships.
    • There is a pointer to the base class through which the virtual function is called.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324953362&siteId=291194637