I have a Cheese class. In my program, I deal a lot with collection of cheeses, mostly vector<Cheese> objects.
I want to be able to eat() a cheese collection, something like this:
vector<Cheese> cheeses;
//cheeses = ...
cheeses.eat();
How to do this? How do I add a new member function to the vector<Cheese> class? Should I just subclass the vector<Cheese> class, name the subclass CheeseCollection and add the member function there, or are there any better ways?
Coming from Objective-C, I’m used to categories, which allowed me to add functions (“methods”) to classes. Is something like that available in C++, or is it considered more natural to subclass like crazy in C++?
In C++ you simply wouldn’t use a member function for this – use a free function:
This is a close equivalent to those Obj-C categories even though the syntax differs (and you’re not using member access).
The standard library container classes weren’t designed to be subclassable so that approach will fail. What you could do is use composition instead of inheritance – i.e. have a
CheeseCollectionclass which contains a vector of cheeses as a member. This may have some advantages, depending on your overall design. However, in general the above is the most C++ic solution.