July 10, 2011

Templates versus Inheritance

Programmers sometimes find it tricky to decide whether to use templates or inheritance. Here are some tips to help you make the decision.

Use templates when you want to provide identical functionality for different types. For example, if you want to write a generic sorting algorithm that works on any type, use templates. If you want to create a container that can store any type, use templates. The key concept is that the templatized structure or algorithm treats all types the same.

When you want to provide different behaviors for related types, use inheritance. For example, use inheritance if you want to provide two different, but similar, containers such as a queue and a priority queue.

Inheritance gets quite useful when designing user interface components -- e.g. when your Application Window inherits from general Window (this type of relationship is called is-a relationship and it's one of the major uses of inheritance).

Similarly for mathematical applications -- say, you want to maximize a function of type y = f(x1, x2, x3). You can do this using various algorithms -- so you can think of implementing a solver with one abstract base class Maximizer w/ virtual member function Solve() and then implement various algorithms as subclasses like BFGS_Maximizer, SimulatedAnnealing_Maximizer, etc. where you implement the actual Solve() member functions.

Another example is mix-in classes, when you want to express your object is "able" to do something -- e.g. a Button is Click able, a Picture is Printable and Zoom able -- here, inheritance (esp. multiple inheritance) comes in handy.

No comments:

Post a Comment