Inheritance versus Composition

C++ Primer 4/e在Defining Base and Derived Classes这个地方有一个关键概念:‘The design of inheritance hierarchies is a complex topic in its own right and well beyond the scope of this language primer. However, there is one important design guide that is so fundamental that every programmer should be familiar with it.

When we define one class as publicly inherited from another, the derived class should reflect a so-called “Is A” relationship to the base class. In our bookstore example, our base class represents the concept of a book sold at a stipulated price. Our Bulk_item is a kind of book, but one with a different pricing strategy.

Another common relationship among types is a so-called “Has A” relationship. Our bookstore classes have a price and they have an ISBN. Types related by a “Has A” relationship imply membership. Thus, our bookstore classes are composed from members representing the price and the ISBN.’


当我们把class定义为“以public形式继承自另一个class”,derived class和base class之间应该反映出所谓的”IS A”关系。在书店例子中,base class代表“以定价售出的书籍”,Bulk_item也是一种书,但有不同的价格策略。

另一个常见的型别关系是”Has A”。书店例中的classes有一个价钱,也有一个ISBN。型别之间的”Has A”关系即代表成员从属关系。书店classes由价格成员和ISBN成员组成。’

IS A 跟 Has A 还可以了解,但是这个复合有关系吗?还没有很清楚?