menu

hjk41的日志

Avatar

Effective C++ 41: Differentiate between templates and inheritance

A template should be used to generate a collection of class when the types of the objects does not affect the behavior of the class's functions.
Inheritance should be used to a collection of classes when the objects does affect the behavior of the class's functions.

Take the stack class for example, the stack class provides push(), pop() and empty() functions, none of which changes its behavior with the content of stack. May it be a stack of ints or a stack of strings or anything else, you can always write pop() like this:


template<class T>
T pop(){
    if(!empty())
        [i]return the top one on the stack[/i]
}

On the other hand, inheritance means another thing. If the type of objects does affect the behavior of the class's functions, we should define the functions as virtual functions so that they do different thing for different objects. Take the class shape for example, all shapes have a draw() function, but they all draw in different ways. rectangle::draw() draws a rectangle, and circle::draw() draws a circle. And inheritance provides exactly what we want. We define shape::draw() as pure vitual, and redefine them in rectangle and circle, and then everything is settled.

Can a stack be implemented using inheritance? The answer is no. If we use inheritance to implement a stack, then what will be the base class like?

class StackBase{
public:
    virtual ??? pop()=0; // what type should pop() return?
    ....
}

评论已关闭