mardi 29 mai 2018

Pushing back a pointer to a vector and then modifying its value affects the pushed value. What should i do instead?

I am using pointers in c++ to achieve polymorphism and I store pointers to the derived classes into a vector. Changing the value of a stored pointer affects the value of all the copies of the same pointer, as it should, however i would like to modify the value of each object individually. Is it possible?

Main class

#include "Cat.h"
#include "Dog.h"
#include <vector>

int main()
{
  std::vector<Animal*> animalVector;

  Animal* animal;
  animal = new Dog();

  animal->setDescription("Good Dog");
  animalVector.push_back(animal);

  animal->setDescription("Bad Dog");
  animalVector.push_back(animal);

  animal = new Cat();

  animal->setDescription("Good Cat");
  animalVector.push_back(animal);

  for (auto& it : animalVector) {
    it->info();
  }
}

Base class

#pragma once

#include <string>

using std::string;

class Animal
{
  protected:
    string mType; //! Holds the type of the Animal
    string mDescription; //! Holds the description of the Animal

  public:

    Animal();
    virtual ~Animal();
    virtual void info();

    virtual void setDescription(string description) {mDescription = description;}
};

Derived class

#pragma once

#include "Animal.h"

class Dog : public Animal
{
  public:
    Dog();
};

Output

Bad Dog
Bad Dog
Good Cat

Desired output

Good Dog
Bad Dog
Good Cat

Aucun commentaire:

Enregistrer un commentaire