I'm currently trying my hand at a project on classes and libraries. Imagine I have the following classes:
- Virtual Class "Animal" as an Interface as a header file
- An expandable number of child classes (Dog, Cat, ...), each as separate files
- A main file in which every existing child of "Animal" gets instanciated, added to a vector and i can loop through the functions specified in the Parent-Class
As an example of the above. The interface "animal.hpp":
class Animal
{
public:
virtual void eat() = 0;
};
One of the implemented creatures (dog.cpp). These should be expandable simply by adding another .cpp-file which are childs of "Animals".
class Dog : public Animal
{
void eat() override
{
std::cout << "Dog eats..." << std::endl;
}
};
And inside the main project something like this. But I don't want to edit this file in order to add new instances of an creature to the vector. (They can all be compiled together but if at runtime is also possible, that would be also interesting.)
int main(int argc, char const *argv[])
{
std::vector<Animal*> creatures;
creatures.push_back(new Dog);
creatures.push_back(new Cat);
for (auto i : creatures)
{
i->eat();
}
return 0;
}
Is this even possible? If so, can someone pinpoint me into the right direction or give me some keywords to search for?
I already tried using the Factory Design pattern but to no success. I stumble over new header files that I would have to include. And in this example (see above) I would also have to add the instances manually.