5/10/2016

Design: Overloading vs. overriding vs. template

Printing shape information requires a function that interacts with various types of shape: circle, polygon, and so on. One way to do this is to have overloaded versions of a function that accepts different type of arguments:

void printShapeInfo(Polygon const &);
void printShapeInfo(Circle const &);

Overloading creates a dependency per version of printShapeInfo to its argument type, but the arguments remain independent from each other. The main drawback is when you add a new shape, for example, ellipse, you also need to add another overload:

void printShapeInfo(Ellipse const &);

And so on for each new type of shape you add.

There are two alternative ways to implement printShapeInfo.

Create a class called Shape. In Shape, declare a pure virtual function description(). Derive Polygon and Circle from it, overriding the inherited member function description().

class Shape {
public:
    virtual std::string description() const =0;
};
class ConvexPolygon : public Shape {

string description() const {…}

};
class Circle : public Shape {

string description() const {…}

};
Write a polymorphic printShapeInfo as follows:

std::string printShapeInfo(Shape const & s){
    return s.description();
}

The type of actual argument the parameter s refers to is determined when the call to printShapeInfo takes place. This late binding or dynamic binding eliminate the need to overload printShapeInfo for any new shape along as it derives from shape (or any of its derived classes). The solution ties Circle and Polygon to Shape: they become siblings by deriving from the same base class.

Lastly, you can avoid the overloading hassle by making printShapeInfo a template function:

template <class T>
std::string printShapeInfo(T const & s){
    return s.description();
}

Of course, you must ensure an argument passed to it has the member function description(); an argument without is flagged as compilation error.

Template keeps Polygon, Circle, etc. independent as in the case of overloading.

1 comment: