Virtual functions make it possible to design and implement systems that are easy to expand. The program can perform general processing on all existing class objects (base class objects) in the hierarchy.
Now we assume that a group of Shape classes (such as circles, squares, and rectangles) are derived from base class shapes. In object-oriented programming, we may want to make every such class Draw its own shape. Although each class has its own Draw function, it is impossible to Draw the Drew function of each shape.
However, no matter what Shape it is, it is best to process it as a base-class Shape object. Then, we only need to call the Drew function of the base class Shape and let the program dynamically determine (that is, the Draw function of the derived class is used during running.
To make this behavior feasible, we need to declare the function Draw in the base class as a virtual function. Then, define Draw in each derived class to Draw a proper shape.
The virtual function declaration method is to add the keyword virtual before the function prototype of the base class. For example, the following may appear in the Shape of the base class:
Virtual void draw () const;
This statement indicates that draw is a constant function that does not take arguments or return values, and is a virtual function.
Then, the program can use the base class pointer or specify the object of the derived class and use the pointer to call the Draw function (for example, shapePr-> draw (). Then, the program dynamically calls the draw function of the derived class, this is called Dynamic Association.
If you use the name and dot member selection operator to reference a specific object to call virtual functions (such as shapeObject. draw (), The called virtual function is determined during compilation, which is static Association.
Programming Skills:
1. To improve program clarity, we 'd better declare these virtual functions at every layer of the class.
2. A derived class without a defined virtual function simply inherits the virtual function of its direct base class.
3. Once a function is declared as a virtual function, even if the virtual function is not declared when the class is redefined, the point will be a virtual function in the subsequent inheritance class layer structure.
Author Li Mu