Search code examples
c++pointersreferencereturnabstract

Returning a child class as their abstract parent class


I am writting a console program in C++. Let's say I have the abstract class Animal, from which the instantiable classes Dog and Cat inherit.

Then I want to create a vector<Animal*>, so that I can go through the whole list of animals I have created and use their virtual function GetName(), which is overloaded in the child classes. Until here everything ok.

Now, I have this function in main() called createAnimal(). I want to make it in such a way that it can return a pointer (or reference) to the parent class, no matter if a Dog or Cat was created. So I wanted to make it like Animal* createAnimal(), but then an error appears telling me 'Animal': cannot instantiate abstract class. How can I return (in any way, pointer, reference) a child class as their abstract parent class?

Thanks in advance!


Solution

  • What you're trying to achieve is called an object factory, but the error message you get means that either you've implemented the function improperly (something like new Animal, while you should never instantiate the abstract base class itself, only its children), or you're using the result improperly (like Animal animal = createAnimal()?)

    So, is your code like this?

    Animal *CreateAnimal(int type) {
        if(type == 1) return new Cat;
    }
    
    std::vector<Animal *> animalVector;
    
    animalVector.push_back(CreateAnimal(1));
    

    Then it should work.