Name Lookup and Inheritance

C++ Primer 4/e在Class Scope under Inheritance这个地方有一个关键概念:‘Understanding how function calls are resolved is crucial to understanding inheritance hierarchies in C++. The following four steps are followed:

1.
Start by determining the static type of the object, reference, or pointer through which the function is called.
2.
Look for the function in that class. If it is not found, look in the immediate base class and continue up the chain of classes until either the function is found or the last class is searched. If the name is not found in the class or its enclosing base classes, then the call is in error.
3.
Once the name is found, do normal type-checking (Section 7.1.2, p. 229) to see if this call is legal given the definition that was found.
4.
Assuming the call is legal, the compiler generates code. If the function is virtual and the call is through a reference or pointer, then the compiler generates code to determine which version to run based on the dynamic type of the object. Otherwise, the compiler generates code to call the function directly.

中文版的这样写:‘了解“函式呼叫如何被决议”对于了解C++继承体系时十分重要。决议动作依以下四步骤进行:

  1. 首先决定呼叫者(object、reference 或 pointer)的静态型别。
  2. 在上述class内搜寻该函式。如果没找到,就往最接近的(immediate)base class寻找,如此上溯classes继承链,直到发现该函式,或直至搜寻到最后一个class。如果都没有发现,表示呼叫有误。
  3. 一旦找到该名称,就根据找到的定义式进行一般的型别检验(7.1.2节,p.229),检查呼叫动作是否合法。
  4. 若呼叫合法,编译器便产出二进制码。如果函式是virtual,且系透过reference或pointer被呼叫,那么编译器产生的码会根据物件的动态型别决定唤起那个版本。否则编译器产生的码会直接唤起该函式。

这个步骤可以作为checklist来coding.