0

I have 3 classes, Player, Monster and Attack.

Class Player
{
  public:
  void addMonster(string line);
  // ...
}


Class Monster
{
 public:
   void addAttack();
   // ...
 private:
   vector <Attack> _attacks;
}

Now, addMonster() creates a new monster mn, and then has mn call its method addAttack() to fill the vector _attacks

void Player::addMonster(string line){
   //...
   Monster mn(line); //creates a new monster
   while(condition){
      mn.addAttack();
   }
}

void Monster::addAttack(){
   //...
   Attack *att = gio->findAttack(ID) //takes the attack from another part of the program
   _attacks.push_back(*att);
}

and it seems to work, if I check the contents of _attacks while inside addAttack(), it is pushing the correct elements in, the size of _attacks changes and evreything, but when the program returns to addMonster(), the _attacks vector of mn is still (or again) empty, as if it had not called the method at all. Why? it's as if the object that gets modified is just a copy of the one calling the method, so the original one is not affected, but then how am I supposed to change that vector of that specific object?

Kytan
  • 1
  • 4
    `Class` wouldn't compile in C++. – Quentin Jun 05 '15 at 14:20
  • 2
    Can you please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us? Because right now it's kind of impossible to say anything for certain. – Some programmer dude Jun 05 '15 at 14:22
  • Does your `operator=` for the Attack class deep copy? You may be creating a new object in `addAttack()` which is then deleted when you exit the scope – Dagrooms Jun 05 '15 at 14:28

1 Answers1

-2

When you create the *att pointer in your addAtack you created it on the stack. Stack variables are deleted when their original function ends and so att is deleted at the and of add attack. One possible workaround for this is to create att on the heap, using the keyword new.

guest1234
  • 5
  • 2