To properly use inheritance you'd want to do something like this:
#include <iostream>
#include <vector>
class Fruit
{
public:
virtual void Eat()
{
std::cout << "Mmm.. a fruit!" << std::endl;
}
virtual ~Fruit() {}
};
class Apple : public Fruit
{
public:
void Eat()
{
std::cout << "Mmm.. an apple!" << std::endl;
}
};
class Pear : public Fruit
{
public:
void Eat()
{
std::cout << "Mmm.. a pear!" << std::endl;
}
};
int main()
{
std::vector<Fruit *> fruits;
fruits.push_back(new Pear());
fruits.push_back(new Apple());
fruits.push_back(new Fruit());
for (int i = 0; i < fruits.size(); i++)
fruits[i]->Eat();
return 0;
}
You need to use pointers to the base class (Fruit *) in order to take advantage of dynamic dispatch. Otherwise, it'll just call the Eat() method of Fruit.
The example in my answer allows for classes that derive from Fruit to override Eat() if they want, but it's not necessary. If you make the virtual function pure, then derived classes must implement it.
class Fruit
{
public:
// Cannot instantiate this class, and derived classes must provide this
virtual void Eat() = 0;
};
Going off of Donotalo's comment, the functionality you want can be implemented as:
class FruitCollection
{
private:
std::vector<Fruit *> fruits;
public:
void Add(Fruit *fruit);
};
void FruitCollection::Add(Fruit *fruit)
{
fruits.push_back(fruit);
}
This is probably overkill in most circumstances, and you'll probably need far more operations than this extremely simple example.