0

I have a class Goblin, which inherits from Enemy.

I'm attempting to run a for loop to set the name of all of the goblins. But the loop isn't settings the names, and I get the default "Enemy".

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Enemy {
    public:
        string getName() {return name; }
        void setName(string _name) { name = _name; }
    private:
        string name = "Enemy";
};

class Goblin : public Enemy {};

int main(int argc, char **argv)
{
    Goblin g1,g2;
    std::vector<Goblin> goblins={g1,g2};
    for (Goblin x : goblins)
    {
        x.setName("test_name");
    }
    std::cout << goblins[0].getName();
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 3
    `for (Goblin x : goblins)` `x` is a copy. You want a reference to the original that you can update. `for (Goblin & x : goblins)` – user4581301 May 05 '20 at 02:50
  • You are an absolute legend! Thank you so much! – AggregationPVP May 05 '20 at 02:54
  • Not a duplicate, but the top answer gives a good rundown of what to use when in a range-based for loop: [C++11 range based loop: get item by value or reference to const](https://stackoverflow.com/questions/15176104/c11-range-based-loop-get-item-by-value-or-reference-to-const) – user4581301 May 05 '20 at 02:55

0 Answers0