Re: inheritance is not for code-reuse (??)
On May 3, 5:52 pm, Bart Simpson <123evergr...@terrace.com> wrote:
I remember reading on parashift recently, that "Composition is for code
reuse, inheritance is for flexibility" see
(http://www.parashift.com/c++-faq-lite/smalltalk.html#faq-30.4)
This confused me somewhat as I have always thought you get code reuse
"for free" with inheritance. Am I missing something?. Will someone care
to explain ??
It depends on what you use inheritance for. In most modern OO
langauges (C++, but also Java, C#, Eiffel, Ada 95...), most
inheritance is inheritance of interface ; a class implements a
specific interface.
In older OO languages (e.g. Smalltalk), there was no static type
checking, and so no need for inheritance of interface. (Put in
other words: you find out about your errors at run-time, not at
compile time.) Historically, too, the coupling inherent in
inheritance wasn't recognized when OO was young, so inheritance
was used a lot when today we would prefer composition.
Basically, code reuse occurs when class A contains an instance
of class B, whether it be by inheritance or composition, and
class B contains implementation code used in the implementation
of class A. Because inheritance implies stronger coupling than
composition, composition is preferred IF all other things are
equal. If they aren't inheritance can be, and still is, used
for this; in C++, such inheritance is generally private.
In most cases of public inheritance (but there are exceptions,
e.g. the templat pattern), the base class contains no
implementation code; it only defines an interface. (It may
contain code defining this interface, for example verifying pre-
or post-conditions.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34