Virtual functions of C ++ Primer Plus learning notes
There are two types of C ++ polymorphism: static polymorphism and dynamic polymorphism. Function overloading and operator overloading are the specific manifestations of static polymorphism. Dynamic polymorphism is the object for dynamically determining the operation during the program running. It is implemented through virtual functions;
1. Concepts of virtual functions:
A pointer to the base class can be used to point to any object derived from the base class, so that multiple implementations of one interface can be accessed; virtual functions are virtual member functions in the base class. They provide an interface. A virtual function can be redefined in one or more Derived classes. However, when a new definition is required in a derived class, the prototype of the virtual function, including the return value, function name, parameter name, number of parameters. The order of parameter types must be identical;
2. How does a late match occur ???
All the work is done by the compiler behind the scenes. To accomplish this, the compiler creates a VTABLE for each class containing virtual functions. In VTABLE, the compiler places the virtual function address of a specific class. In each class with a virtual function, the compiler secretly sets a pointer to the VTABLE that the VPTR points to this object. When using a base class pointer for a virtual function call, the compiler obtains the VPTR through static insertion and searches for the code of the function address in the VTABLE table.
3. Virtual features:
The key to implementing polymorphism in runtime using virtual functions is that the pointer to the base class must be used or referenced to access the virtual function.
Note:
Redefining the virtual function of the base class in a derived class is another special form of function overloading, which is not a general function overload. When you reload a common function, only the function name must be the same, but when you reload a virtual function, the function name, return type, number of parameters, parameter type, and Parameter order must be the same, otherwise, virtual features will be lost;
#include
using namespace std;class figure{public:void set(double i=0,double j=0){x=i;y=j;}virtual void show_area(){cout<<"No area computation defined for this class"<
set(10,5);f->show_area();f=&s;f->set(10,5);f->show_area();f=&c;f->set(10);f->show_area();return 0;}
Running result:
Triangle with high 10 and base 5 has an area of 25
Square with dimension 10*5 has an area of 50
Circle with radius 10 has an area of 314