menu

hjk41的日志

Avatar

Effective C++ 40: Model "has-a" or "is-implemented-in-terms-of" through layering

Layering is the process of building a class on top of another by having the layering class contain an object of the layered class as a data member.
If we want to write a class CSet, and use the list template in STL to store the data, we have two choices: to use layering or use inheritance.


// two implementions of CSet
// 1. layering
template<class Type> class CSet{
public:
    ...
protected:
    list<Type> m_data;
}

// 2. inheritance
template<class Type> class CSet:public list<Type>{
...
}


There are two major problems with the second implemention.
First, public inheritance means "isa", but a set is not a list. Lists can have duplicates while lists can't. If we insert two "123" into a list, the list will contain two "123". However, if we insert two "123" into a set, the second insertion will fail.
Second, when CSet inherits from list, it inherits all the member functions, thus we can do the follow to the second implemention of CSet:

CSet<int> set;
set.push_back(12);


This is totally non-sense, for a set don't have a "front" nor a "back".
So if we are modeling "has-a" or "is-implemented-in-terms-of", we better use layering.

Above is the argument of the author, but I am still not fully convinced, can we use protected inheritance? And what does protected inheritance mean?

评论已关闭