Boost logo

Boost :

From: Joel de Guzman (joel_at_[hidden])
Date: 2007-10-08 19:24:54


Simonson, Lucanus J wrote:
> Marco wrote:
>> If I can ask, why do you preferred subclassing instead of composition?
>> Could 'b' be a member of 'a' instead?
>> Perhaps to access protected members of class b otherwise inaccessible?
>> In another part of your thread you say inerithance is public just
>> because of a limitation in MS compiler, so your intention would be to
>> use private inerithance, so you don't think at 'a' as is 'b' but in is
>> implemented in terms of 'b', is this correct?
>
> This is the kind of question I wanted asked. Gyuszi suggested
> composition early on. I don't really have a good rationale for choosing
> inheritance over composition. At the time, private inheritance was
> working fine in gcc 4.2.0 and I was able to make the design pattern
> using inheritance from the template parameter do everything I wanted. I
> didn't need to access protected members of b. You are correct that I
> could have made the design pattern work equally well, perhaps better,
> using composition instead of inheritance. All that I need is for a to
> be able to safely cast to b and visa-versa. I specifically made this
> type of code change easy to make by abstracting away the mechanism for
> accessing the data, but what benefit would I get from changing the
> design pattern to use composition instead of inheritance? It just isn't
> clear to me what it is about inheritance that is objectionable in this
> case. Perhaps this is a learning opportunity for me.

Ok I posted something but realized I wasn't answering your question
why inheritance (nor composition) is desirable when adapting.
Here's a strong case...

I have a legacy API with an opaque point type:

     struct point; // hah! opaque, details hidden

     // getter API
     float get_x(point const&);
     float get_y(point const&);

Another example would be STL iterators where a pointer can
model a random access iterator. Nope, you can't subclass from
a pointer.

Regards,

-- 
Joel de Guzman
http://www.boost-consulting.com
http://spirit.sf.net

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk