Reputation: 651
Simple question here. I have to define classes that will contain sets of books, movies, CDs. I defined a template class, say Set<T>
, with all the common methods, and then defined classes that derive from a particular instance (is it the correct term?) of the Set
class
class Movies_set : public Set<Movie>
{
/* ... */
}
in which I define some other methods (say a function to search for actors). Is it a good programming technique or are there more convenient methods?
Upvotes: 0
Views: 153
Reputation: 320
It depends on what Set actually is. I suspect Set is something similar to std::set and in that case, I would advice against derivation and steer you towards composition.
The reason deriving from Set is a bad idea is because it exposes the API of set, which has nothing to do whatsoever with MovieSet. If you need methods to make searches to your MovieSet object, implement them on MovieSet itself, especially since, as you pointed out, you are going to augment MovieSet's interface.
This way, you would also gain something very powerful : encapsulation. If for some reason you decide to change from a Set to a std::map, the interface of your base class is likely to change and any code that accesses MovieSet will be impacted. If you had stored Set as a private data member, you would not run into this issue, as you would have already defined MovieSet's appropriate accessors.
That of course, if all based on my premise that Set is actually just a container.
Upvotes: 3
Reputation: 16148
if Movie_set doesn't add any over the implementation of Set then it is a waste of time deriving from Set
you are better of typedefing it.
typedef Set<Movie> movie_set;
like that. However if you are specializing the Set further with new member functions and data members then the is ok, although deriving from containers ins't common (usually you own them). but Also long as the necessary function are virtual (destructor) it should be ok.
Upvotes: 0
Reputation: 361362
This is absolutely fine.
In fact, there is a well-known pattern which does almost similar thing, except that it uses the derived class itself as the type argument to the base class template:
Upvotes: 0
Reputation: 38825
This is absolutely nothing wrong with doing this, and it's quite a common idiom. That said, you might want to make sure that a typedef
is sufficient enough. If your Movies_set
adds no new specific functionality, it's probably better to:
typedef Set<Movie> Movies_Set;
Obviously, if Movies_set introduces specific functionality pertinent to movies, the inheritance is the way to go.
Upvotes: 0