Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Inheritance vs Delegation: pros and cons

by gmax (Abbot)
on Jul 28, 2003 at 10:20 UTC ( #278382=note: print w/replies, xml ) Need Help??

in reply to Inheritance vs Delegation: pros and cons

It is a problem of semantics.

I use inheritance whenever the parent class is a generalization of the descending class. The example given in Class::Delegation is not well chosen. A car can't inherit from a wheel. A car contains wheels. In this case you use delegation.

The appropriate example would be a class vehicle, from which you inherit to create car, truck, tractor, and so on. In this case, it makes sense to use inheritance.

My rule of thumb is, if it makes sense to say derived class IS A parent class, you inherit, otherwise you include the other class inside yours.

It makes sense to say a car is a vehicle, but it does not make sense to say a car is a wheel. Somebody could say that "a car is a wheel, a brake, an engine, and so on," and inherit from all the components. But also a washing machine can have wheels, engines and brakes, but it is not a car. Thus, the inheritance paradigm doesn't apply, and forcing it in such a case can only create confusion.

 _  _ _  _  
(_|| | |(_|><
  • Comment on Re: Inheritance vs Delegation: pros and cons

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://278382]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2022-11-26 12:09 GMT
Find Nodes?
    Voting Booth?