关于继承,你要知道的

What are some disciplines for using multiple inheritance? M.I. rule of thumb #1: Use inheritance only if doing so will remove if / switch statements from the caller code. Rationale: this steers people away from “gratuitous” inheritance (either of the single or multiple variety), which is often a good thing. There are a few times when you’ll use inheritance without dynamic binding, but beware: if you do that a lot, you may have been infected with wrong thinking. In particular, inheritance is not for code-reuse. You sometimes get a little code reuse via inheritance, but the primary purpose for inheritance is dynamic binding, and that is for flexibility. Composition is for code reuse, inheritance is for flexibility. This rule of thumb isn’t specific to MI, but is generic to all usages of inheritance. M.I. rule of thumb #2: Try especially hard to use ABCs when you use MI. In particular, most classes above the join class (and often the join class itself) should be ABCs. In this context, “ABC” doesn’t simply mean “a class with at least one pure virtual function”; it actually means a pure ABC, meaning a class with as little data as possible (often none), and with most (often all) its methods being pure virtual. Rationale: this discipline helps you avoid situations where you need to inherit data or code along two paths, plus it encourages you to use inheritance properly. This second goal is subtle but is extremely powerful. In particular, if you’re in the habit of using inheritance for code reuse (dubious at best; see above), this rule of thumb will steer you away from MI and perhaps (hopefully!) away from inheritance-for-code-reuse in the first place. In other words, this rule of thumb tends to push people toward inheritance-for-interface-substitutability, which is always safe, and away from inheritance-just-to-help-me-write-less-code-in-my-derived-class, which is often (not always) unsafe. M.I. rule of thumb #3: Consider the “bridge” pattern or nested generalization as possible alternatives to multiple inheritance. This does not imply that there is something “wrong” with MI; it simply implies that there are at least three alternatives, and a wise designer checks out all the alternatives before choosing which is best.less