Suppose you have classes Apple, Orange and Pear that all inherit from a base class Fruit. And suppose your software has modules that work with vector<Apple>, vector<Orange> and vector<Pear>. Now I'd like to write a generic class FruitStore having a public method addToShelves which takes a vector of fruit and puts it on shelves for sale:
But I'm pretty darn sure you can't pass a vector<Apple> to a function expecting a vector<Fruit> (even though such a thing makes sense intuitively). And similarly you can't add a vector<Apple> to a vector<vector<Fruit>>. This is because vector<Apple> does not inherit from vector<Fruit>.Code:class FruitStore { private: vector<vector<Fruit>> shelves; public: void FruitStore::addToShelves(vector<Fruit>& fruitList) { shelves.push_back(fruitList); } }
It's been quite sometime since I've written any C++ (and hopefully you can see past any gross syntactic errors I've made above), but is there any technique one can use to store all these fruit vectors in a single shelf container without having to actually copy, say, each Apple in a vector<Apple> into a new vector<Fruit> (which really seems like a silly thing to have to do)?
Thanks much,
Matt Busche