Search code examples
c++vectorpolymorphismunique-ptr

How to cast vector of unique_ptr in a more generic way


The code:

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class Animal
{
    protected:
        // protected constructor, so it should be constructed from the derived class
        Animal(int animalProp):
            myAnimalProp(animalProp)
        {
        }
        
        Animal(const Animal &animal):
            myAnimalProp(animal.myAnimalProp)
        {
        }
        
        Animal(Animal &&animal):
            myAnimalProp(animal.myAnimalProp)
        {
        }
        
    public:
        virtual void whoAmI() const
        {
            cout << "Animal" << endl;
        }
        
        virtual void setAnimalProp(int val)
        {
            myAnimalProp = val;
        }
        
        virtual int getAnimalProp() const
        {
            return myAnimalProp;
        }
        
    protected:
        int myAnimalProp = 0;
};

class Dog: public Animal
{
    public:
        Dog(int animalProp, int dogProp):
            myDogProp(dogProp),
            Animal(animalProp)
        {
        }
        
        Dog(const Dog &dog):
            myDogProp(dog.myDogProp),
            Animal(dog)
        {
        }
        
        Dog(Dog &&dog):
            myDogProp(dog.myDogProp),
            Animal(move(dog))
        {
        }
    
        virtual void whoAmI() const override
        {
            cout << "Dog" << endl;
        }
        
        virtual void setAnimalProp(int val) override
        {
            myAnimalProp = val + 10;
        }
        
        virtual int getAnimalProp() const override
        {
            return myAnimalProp;
        }
        
        void setDogProp(int val)
        {
            myDogProp = val;
        }
        
        int getDogProp() const
        {
            return myDogProp;
        }
        
    private:
        int myDogProp = 10;
};

class Cat: public Animal
{
    public:
        Cat(int animalProp, int catProp):
            myCatProp(catProp),
            Animal(animalProp)
        {
        }
        
        Cat(const Cat &cat):
            myCatProp(cat.myCatProp),
            Animal(cat)
        {
        }
        
        Cat(Cat &&cat):
            myCatProp(cat.myCatProp),
            Animal(move(cat))
        {
        }
    
        virtual void whoAmI() const override
        {
            cout << "Cat" << endl;
        }
        
        virtual void setAnimalProp(int val) override
        {
            myAnimalProp = val + 20;
        }
        
        virtual int getAnimalProp() const override
        {
            return myAnimalProp;
        }
        
        void setCatProp(int val)
        {
            myCatProp = val;
        }
        
        int getCatProp() const
        {
            return myCatProp;
        }
        
    private:
        int myCatProp = 20;
};

class AnimalShop
{
    public:
        AnimalShop()
        {
            myAnimals.push_back(make_unique<Dog>(1, 11));
            myAnimals.push_back(make_unique<Cat>(1, 21));
            myAnimals.push_back(make_unique<Dog>(1, 12));
        }
        
        vector<unique_ptr<Animal>> getAllAnimals()
        {
            vector<unique_ptr<Animal>> animals;
            
            for (const unique_ptr<Animal>& animal: myAnimals)
            {
                // I cannot do so
                // because it will try to call the copy constructor of Animal
                // and I want to call the copy constructor of derived class
                // not to mention the copy constructor is in protected scope
                
                //animals.push_back(make_unique<Animal>(*animal));
                
                if (const Dog *dog = dynamic_cast<const Dog *>(animal.get()))
                {
                    animals.push_back(make_unique<Dog>(*dog));
                }
                else if (const Cat *cat = dynamic_cast<const Cat *>(animal.get()))
                {
                    animals.push_back(make_unique<Cat>(*cat));
                }
            }
            
            return animals;
        }
        
    private:
        vector<unique_ptr<Animal>> myAnimals;
};

int main()
{
    cout << "Starting" << endl;
    
    AnimalShop animalShop;
    vector<unique_ptr<Animal>> animals_000 = animalShop.getAllAnimals();
    for (const unique_ptr<Animal> &animal: animals_000)
    {
        animal->whoAmI();
        animal->setAnimalProp(2);
        cout << "Animal Prop: " << animal->getAnimalProp() << endl;
    }
    
    vector<unique_ptr<Animal>> animals_001 = animalShop.getAllAnimals();
    for (const unique_ptr<Animal> &animal: animals_001)
    {
        animal->whoAmI();
        cout << "Animal Prop: " << animal->getAnimalProp() << endl;
    }
   
    cout << "Ending" << endl; 
   
    return 0;
}

Indeed, my question is about the function AnimalShop::getAllAnimals().

I want to get all the animals in the shop without transferring the ownership to the caller, so I copy all of them and return them.

But I cannot do it in the following way with the reason stated in the comment in the code:

animals.push_back(make_unique<Animal>(*animal));

Instead, I need to do it in a more wordy way:

if (const Dog *dog = dynamic_cast<const Dog *>(animal.get()))
{
    animals.push_back(make_unique<Dog>(*dog));
}
else if (const Cat *cat = dynamic_cast<const Cat *>(animal.get()))
{
    animals.push_back(make_unique<Cat>(*cat));
}

Is there any better way to do so?

A further question, for casting vector<unique_ptr<Base>> from/to vector<unique_ptr<Derived>>, is there any way to do it without a for loop?

Any help is highly appreciated.


Solution

  • Yes, there's a better way. The common solution - if/when you want a deep copy (like your current getAllAnimals() creates) - is to add a virtual function in the base class like this:

    virtual std::unique_ptr<Animal> clone() = 0;
    

    Then each type of derived class can implement clone() to provide a copy of itself. getAllAnimals() can then loop over myAnimals calling clone and push the unique_ptrs into a new container to return.

    (I'm assuming your purpose is to get a deep copy - independent from the objects in myAnimals, for some other purpose. To call a function that should be const like whoAmI() on the objects you don't need a deep copy... you could give AnimalShop() a vector<unique_ptr<Animal>>::const_iterator begin() const { return myAnimals.begin(); } and similar ...end... function, then you could write for (const auto& animal : animalShop) animal->whoAmI();.)