Strange error in c ++ class

1

I have the following code:

#include <iostream>
using namespace std;
class guns{
public:
    string name;
    int ammo;
    void reload(){
        ammo = pente;
    }
    void shoot(){
        ammo -= 1;
    }
private:
    int pente = ammo;
};
int main(){
guns fuzil;
fuzil.name = "M-16";
fuzil.ammo = 50;
cout << "O fuzil " << fuzil.name << " tem " << fuzil.ammo << endl;
fuzil.shoot();
fuzil.shoot();
cout << "ammo: " << fuzil.ammo << endl;
fuzil.reload();
cout << "carregado: " << fuzil.ammo;
}

The output is:

O fuzil m16 tem 50
ammo: 48
carregado: 31

Because when reload () is executed 'ammo' has the bizarre value 31?

    
asked by anonymous 10.01.2018 / 13:37

1 answer

1

Work with builders , the problem is that when you declare your variable, it constructs without value because you had no constructor method for that. When I compiled your program and debugged pente it returned 0.

With the constructor class you pass all the attributes at the moment of distancing the class and already assign to itself, I added the following lines:

 guns(string _name,int _ammo)
:name(_name),ammo(_ammo),pente(_ammo){}

In it, you are creating a constructor that asks for a string (name) and an int (ammo) and then assigns the class, so the value of pente will be assigned soon after the value of ammo be assigned as well. Here is the final result:

#include <iostream>
using namespace std;
class guns{
public:

    guns(string _name,int _ammo):
    name(_name),ammo(_ammo),pente(_ammo){}

    string name;
    int ammo;
    void reload(){
        ammo = pente;
    }
    void shoot(){
        ammo -= 1;
    }
private:
    int pente = ammo;
};

int main(){
    guns fuzil("M-16",50);
    cout << "O fuzil " << fuzil.name << " tem " << fuzil.ammo << endl;
    fuzil.shoot();
    fuzil.shoot();
    cout << "ammo: " << fuzil.ammo << endl;
    fuzil.reload();
    cout << "carregado: " << fuzil.ammo;
}
    
10.01.2018 / 14:01