mercredi 25 février 2015

C++11 vector of smart pointer

Suppose we have the following codes. We have following classes



  • Animal as AbstractClass

  • Dog and Bird which is subclass of Animal

  • Zoo which keeps all animals


_



class Animal
{
public:
Animal();
void HasWings() = 0;
};

class Bird : public Animal
{
public:
Bird() : Animal() {}
void HasWings() override { return true; }
};

class Dog : public Animal
{
public:
Dog() : Animal() {}
void HasWings() override { return false; }
};

class Zoo
{
public:
Zoo() {}
void AddAnimal(Animal* animal) { _animals.push_back(animal); }
...
std::vector<Animal*> _animals;
};

void myTest()
{
Zoo myZoo;
Bird* bird = new Bird();
Dog* dog = new Dog();

myZoo.AddAnimal(bird);
myZoo.AddAnimal(dog);

for (auto animal : myZoo._animals)
{
...
}
...
}


I hope to replace vector of pointers by vector of smart pointers. i.e,



std::vector<std::shared_ptr<Animal>> _animals;


How do we change the code for Zoo and myTest? I find difficulty on updating the code, especially the method "AddAnimal" in Zoo class



auto bird = std::make_shared<Bird>();
auto dog = std::make_shared<Dog>();
myZoo.AddAnimal(bird);
myZoo.AddAnimal(dog);


bird and dog are different type


Aucun commentaire:

Enregistrer un commentaire