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

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.

主站蜘蛛池模板: 庆元县| 道真| 理塘县| 衡阳市| 巴塘县| 遂昌县| 高台县| 连州市| 伊金霍洛旗| 蚌埠市| 平原县| 沭阳县| 金昌市| 万载县| 平利县| 庆安县| 海原县| 兰溪市| 临沧市| 宁安市| 晴隆县| 沛县| 拉萨市| 莱西市| 苏尼特右旗| 兴山县| 岫岩| 吉安市| 毕节市| 寻甸| 长治县| 彝良县| 类乌齐县| 苗栗市| 武乡县| 四子王旗| 西乌珠穆沁旗| 平舆县| 云梦县| 南京市| 中江县|