Home > Article > Backend Development > C++11 new features - polymorphism and virtual functions, override specifier
Polymorphism and virtual functions
Polymorphism is one of the important features of C, and it is also a feature that is difficult for beginners to understand. Let’s look at a simple example first:
The code is very simple. According to the author’s own words, describe the key points from the definition to the function of polymorphism in the above code. It should be It won’t be simpler anymore, starting from the main function:
Pointer to the base class
These three points are necessary conditions, and one of them is indispensable.
There are other interesting aspects of the above code. Although it does not affect the results, it is still good to understand them. When redefining (overriding) the virtual function in the base class in the derived class:
virtual keyword is not required
Override failure
Override of virtual function It is required that the signatures of the two functions must be consistent. For example, the following code:
Since the signature of sub2::f1 is inconsistent with the signature of base::f1, polymorphism cannot be achieved.
Maybe you will think that this error is too obvious and will never happen. That's because the member function in this example is too simple. In actual development, with the expansion of development scale, the inheritance relationship of classes will become deeper and deeper, and the parameters of member functions will also become more and more. We often encounter the signatures and overrides of member functions defined in derived classes. The signature of the object is inconsistent, resulting in overwriting failure.
And the terrible thing is that this kind of error will not produce compilation errors and is not easy to find.
override specifier
In order to solve this problem, a method was introduced in C 11: use the override specifier when declaring and defining override functions in derived classes:
Due to the clear purpose of the function, when the compiler cannot find a virtual function with the same signature in the base class, a compilation error will occur.
The author feels
It should become a habit of C programmers to make better use of the functions of the language itself and not give up any opportunity to automatically detect errors. It can also be regarded as the embodiment of craftsman spirit.
Related articles:
Talk in detail about the c 11 final and override specifiers
The differences and connections between auto and decltype in the new features of C 11
Related videos:
The above is the detailed content of C++11 new features - polymorphism and virtual functions, override specifier. For more information, please follow other related articles on the PHP Chinese website!