Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Check a Variable Within a Class?

I’m just starting to learn about C++ classes, and I had a question regarding how to check a variable for each object without cycling through them using if-statements.
Here is my code:

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


    class Weapon {
    
    public:
        string name;
        int damage;
        bool isCurrentWeapon;
        
        
    public:
    
    Weapon(string n, int d, bool iCW){
        name = n;
        damage = d;
        isCurrentWeapon = iCW;
    }
    };


    int main()
    {
    Weapon sword("Sword",30,true);
    Weapon dagger("Dagger",10,false);
    cout<<"Welcome to the Weapon Shop! Your current weapon is: " XXXXXXX
    return 0;
    }

My question is how would I replace the XXXXXXX with the current weapon? I’d like to somehow check out of ALL of the objects in the class, which one has isCurrentWeapon set to true. And I’d like to do this without using if-statements to individually check each weapon.

I tried to use a static variable, but I decided that that probably wasn’t right, as each instance of Weapon has the variable isCurrentWeapon.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

(If there is a better title for this question please edit it – I just couldn’t think of a way to describe it better.)

>Solution :

isCurrentWeapon shouldn’t be a member of the class. You should instead keep a pointer outside the class that points to whichever weapon is the current one.

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


class Weapon {

public:
    string name;
    int damage;        
    
public:

Weapon(string n, int d, bool iCW){
    name = n;
    damage = d;
}
};

Weapon* currentWeapon;


int main()
{
Weapon sword("Sword",30,true);
Weapon dagger("Dagger",10,false);
currentWeapon = &sword;
cout<<"Welcome to the Weapon Shop! Your current weapon is: " << currentWeapon->name;
return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading