Personally, I think that a big reason why C is suitable for architectural design is that it can program for the future. For example, you can limit the access of derived classes to base class members through public/protected/private, and you can define interfaces that abstract classes require derived classes to implement, etc.
When we declare/define a virtual function, the derived class can choose to override the virtual function or not. Regarding this point, C also provides the necessary methods to require derived classes to override certain methods, which can also be regarded as a kind of future programming.
Pure virtual function
This is not a new technology, and its function is very simple: once a base class declares a pure virtual function, its derived The class must override this function when it is instantiated.
In this example, the sub::f1() method is commented out, so a compilation error will occur on line 27.
final specifier
Generally speaking, if there is a required override method, there should be a means to prohibit override. But I don’t know why, this feature was only introduced in C 11. The method of use is also very simple: just add the final specifier after the function declaration.
The code is basically unchanged, except that the final specifier is replaced after the base::f1() statement. At this time, if the sub::f1() method is defined, a compilation error as shown above will occur.
Author's point of view
This article puts pure virtual functions and final specifiers together for explanation based on the author's personal understanding. If there are any inaccuracies, please feel free to add and correct them.
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 - usage of pure virtual functions and final specifiers. For more information, please follow other related articles on the PHP Chinese website!