# OOAD Lab 2.6, 3 (03/09) ###### tags: `OOAD` --- [TOC] --- ## 2.6. Why You Should Not Abuse Inheritance over Composition - **Inheritance** vs. **Composition** - when you try to find answer for OOAD problem it is always about **FUTURE** - Bad of "Abuse Inheritance over Composition" 1. **Inherit all the method and interfaces of vector** - all of them can be override? - **A class only carry the methods needed** 2. **Polymorphism freedom can kick your ass** 3. **Copy-paste program** - when **"has-a" or composition relationship changed**, you cannot reuse most of the code - need to do copy-paste program ## 3. Polymorphism - **多型:就是當你可以用基底 class 的指標或參考來進行處理時,卻可以依照其 subtype 來進行不一樣的事情**(其實多形是很難用解釋的) - **C++ 中任何想要被繼承的 class overridden 的 method 都要宣告成 virtual** - **一個function 一旦宣告成virtual,則在繼承的class 中也是 virtual**。但是可以忽略不寫,不過建議要寫 - **多型只對 pointer, reference(a base class points to a subclass object), 以及宣告為 virtual 的 function 有效** - **如果一個 class 有任何一個 method 宣告為 virtual 則 destructor 也應該宣告為 virtual** ,這為了確保正確的 destructor 做正確的清除 - Why not declare all methods as virtual? - This could be done, but **involves additional overhead.** - **Object slicing**: - when **pass-by-value (copy)** from subtype to base type - **only base type part of a subclass instance gets copied** - **4 basic element of OOP** - object & message - inheritance - encapsulation - dynamic binding (via polymorphism) - **polymorphism? vs. overloading**\ - **polymorphism**:函示在執行的時候,面對不同的型別或物件,能有自動相對應的操作及功能 - **overloading**:多出來的功能,是在於可以真正的以一段同樣的程式碼對不同的 資料型別或物件進行操作 - 在物件導向的語言中,**polymorphism (多型) 是inheritance, message passing 所自然結合產生的結果**: - **switch patterns** - 耦合性過高 - **---> function pointers** - `int (*f)(int, int);`, `int (*f[])(int,int);` - **---> dynamic binding(動態連結)** - binding of compiler and linker (logical address) - compilation time binding - linking time binding - **indirect call** - dynamic linking library (DLL) - external reference table: `ExTbl[index] => run time address - **virtual function table** - Dynamic binding via polymorphism - **virtual function table** - **if there is a virtual function, a pointer `vptr` (per instance) to a virtual function table (per class) is generated** - **Virtual Base Class (Abstract class)** - In C++, **class that has member functions are pure virtual function** - e.g. `virtual void foo() = 0;` - **沒有 instance,不能 new** - 用多重繼承,**那麼只要這個 class 可能有兩個以上的 derived class 則你應該在繼承他的時候在前面加上 virtual** - **只有繼承沒有多型,不是物件導向** - 核心程式與 subtype 無關