When to use delegation instead of inheritance?

Cuga picture Cuga · May 7, 2009 · Viewed 27.3k times · Source

Could someone please explain when would I want to use delegation instead of inheritance?

Answer

Anzurio picture Anzurio · May 7, 2009

When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.

One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.