官术网_书友最值得收藏!

Inheritance

In addition to allowing you to organize code into objects, classes also allow for classes to serve as a template for other classes through the use of polymorphism. In C++, we can combine the properties of any number of classes into a new class, giving it custom properties and methods as well.

This is a very effective way to create user-defined types (UDTs), especially when combined with operator overloading to use common operators to define operations for addition, subtraction, and so on for the UDT.

Inheritance in C++ follows the following pattern:

class B : public A { // Private members. public: // Additional public members. }; 

Here, we declare a class, B, which derives from class A. This allows us to use any public methods defined in class A on an instance of class B, as if they were defined in the latter to begin with.

All of this seems fairly easy to understand, even if things can get a bit confusing the moment we start deriving from more than one base class. However, with proper planning and design, polymorphism can be a very powerful tool.

Unfortunately, none of this answers the question of how much overhead the use of polymorphism adds to our code. We saw earlier that C++ classes by themselves add no overhead during runtime, yet by deriving from one or more base classes, the resulting code would be expected to be significantly more complex.

Fortunately, this is not the case. Much like with simple classes, the resulting derived classes are simple amalgamations of the base structs that underlie the class implementations. The inheritance process itself, along with the validation that comes with it, is primarily a compiler-time issue, bringing with it various benefits for the developer.

主站蜘蛛池模板: 澳门| 通道| 嵊州市| 西宁市| 汾阳市| 杭锦后旗| 北宁市| 普兰店市| 渭南市| 新邵县| 德化县| 文水县| 紫金县| 阜南县| 福安市| 渝北区| 汝州市| 大理市| 永和县| 南澳县| 乌兰浩特市| 大兴区| 龙海市| 濮阳市| 西华县| 黄冈市| 孟州市| 北安市| 浠水县| 余干县| 兴安盟| 甘孜县| 炉霍县| 阳城县| 永胜县| 巩义市| 开封县| 旬邑县| 达州市| 宁夏| 泾源县|