Respecting the Base-Class Interface

C++ Primer 4/e在Defining Base and Derived Classes这个地方有一个关键概念:‘The reason that a constructor can initialize only its immediate base class is that each class defines its own interface. When we define Disc_item, we specify how to initialize a Disc_item by defining its constructors. Once a class has defined its interface, all interactions with objects of that class should be through that interface, even when those objects are part of a derived object.

For similar reasons, derived-class constructors may not initialize and should not assign to the members of its base class. When those members are public or protected, a derived constructor could assign values to its base class members inside the constructor body. However, doing so would violate the interface of the base. Derived classes should respect the initialization intent of their base classes by using constructors rather than assigning to these members in the body of the constructor.’

中文版的这样写:‘建构式只能初始化直接继承的base class,因为每个class都定义了自己的介面。当我们定义Disc_item,我们定义其建构式,指明如何初始化Disc_item。一旦class定义其介面,所有与该class物件的任何互动都应该透过其介面进行,即便这些物件是derived 物件的一部分。

基于类似原因,derived class建构式不能对其base class成员进行初始化,也不该对它们赋值。如果这些成员是public或protected,derived建构式(就语法而言)可在函式主体内赋值给其base class成员。然而这么做会违反base介面。Derived classes应该改用建构式,遵从其base classes的初始化方式,而非在自己的建构式主体内直接赋值给那些成员。’

纪录之。