polymorphism and virtual functions
Polymorphism is one of the most important features of C + +, and it is also difficult for beginners to understand. Let's look at a simple example:
The code is very simple, according to the author's own description of the above code in the polymorphism from the definition to the point of action, should not be simpler, from the main function to look at:
Pointer to base class
Objects that point to derived classes
- A derived class overrides a virtual function defined in a base class
These three points are necessary and indispensable.
There are other interesting things about the code above, although it doesn't affect the results, but it's good to know. When a virtual function in a base class is redefined (overridden) in a derived class:
Virtual keywords are not required
You do not have to declare a function public
Overwrite the failure condition
Overriding a virtual function requires that the signatures of the two functions be identical. For example, the following code:
Polymorphism cannot be achieved because the signature of the SUB2::F1 is inconsistent with the signature of the BASE::F1.
You may think that this mistake is too obvious and will not happen at all. That's because the member functions in this example are too simple. In the actual development with the expansion of the scale of development, the inheritance of the class will become more and more deep, the parameters of the member functions will be more and more, often encountered in the derived class defined in the member function of the signature and overwrite the object's signature is inconsistent, resulting in overwrite failure.
What's more, this error does not create a compilation error and is not easily detected.
Override specifier
To solve this problem, C++11 introduces a method that uses the override specifier when declaring, defining, overriding functions in a derived class:
Because of the purpose of the explicit function, a compilation error occurs when the compiler cannot find the virtual function of the same signature in the base class.
Author experience
Better use of the language itself, do not give up any chance of automatic error detection, this should become the habit of C + + programmers. It is also the embodiment of the spirit of the craftsman.
Related articles:
Details c++11 final and override specifiers
Auto and Decltype differences and linkages in c++11 new features
Related videos:
Android6.0 new Features