-4

I recently realized how rusty I have gotten at C++ so I decided to work on a small text-based RPG. I have a class for weapons and a class for a player. My default Player constructor is this:

Player::Player()
{
    name = "Henry";
    hp = 50;
    mp = 25;
    xp = 0;
    Weapon wep = Weapon::Weapon("Club", 5);
}

I have two constructors for my weapons, as follows:

Weapon::Weapon()
{
    name = "Hands";
    damage = 1;
}
Weapon::Weapon(string n, int d)
{
    name = n;
    damage = d;
}

My Weapon class:

class Weapon
{
private:
    string name;
    int damage;
public:
    Weapon();
    Weapon(string n, int d);
    string getName();
    int getDmg();
};

The problem, however, is when I call the getName() function in my main file, it returns "Hands". Likewise, getDmg() returns 1. Is this normal or did I do something wrong?

apquint
  • 1
  • 1
  • 1
    That is neither the correct mechanism for initializing a Weapon, nor the correct target of said-initialization. `wep` is a local variable in `Player::Player()`, and as-such, its lifetime is considerably more limited than I bet you intended. – WhozCraig Dec 12 '14 at 21:54
  • **Books:** http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Galik Dec 12 '14 at 22:10

1 Answers1

4

Weapon wep = Weapon::Weapon("Club", 5); is local to your Player constructor, you probably mean wep = Weapon("Club", 5); or even better:

Player::Player() :
    name("Henry"),
    hp(50),
    mp(25),
    xp(0),
    wep("Club", 5)
{
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302