Effective C++ item 38: Model "has-a" or "is-implemented-in-terms-of" through composition

Item 32 explains that public inheritance means “is-a”. Composition has a meaning, too. Actually, it has two meanings. Composition means either “has-a” or “is-implemented-in-terms-of”. That’s because you are dealing with two different domains in your software. Some objects in your programs correspond to things in the world you are modeling, e.g., people, vehicles, video frames, etc. Such objects are part of the application domain. Other objects are purely implementation artifacts, e.g., buffers, mutexes, search trees, etc. These kinds of objects correspond to your software’s implementation domain. When composition occurs between objects in the application domain, it expresses a has-a relationship. When it occurs in the implementation domain, it expresses an is-implemented-in-terms-of relationship.

For example, if you want to implement set, you won’t inherit from list. Instead, you will use list as the implementation of your own set class.

1
2
3
4
5
6
7
8
9
10
template<class T>
class Set {
public:
bool member(const T& item) const;
void insert(const T& item);
void remove(const T& item);
std::size_t size() const;
private:
std::list<T> rep;
};

Reference:
“Effective C++” Third Edition by Scott Meyers.