Is there any way to call a class instead of the object within the class?

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class invItem {
int weaponMaxDam, weaponMinDam, itemPrice;
string weaponName;
public:
   invItem (int,int,int,string);
   int maxDam () {return weaponMaxDam;}
   int minDam () {return weaponMinDam;}
   int meanDam () {return ((weaponMaxDam+weaponMinDam)/2);}
   int price () {return itemPrice;}
   string itemName() {return weaponName;}
};

invItem::invItem (int a, int b, int c, string d){
    weaponMaxDam = a;
    weaponMinDam = b;
    itemPrice = c;
    weaponName = d;
}

invItem shortSword (3,9,3,"shortsword");

void shopEnter ()
{
    cout << endl << "What would you like to buy?" << endl;
    cin >> playerInput;
                if (playerInput == "?"){
                    cout << endl << "The Shop contains" << endl << shortSword.itemName() << " - " << shortSword.price() << endl ;
                    shopEnter ();}
                 else if (playerInput == shortSword.itemName())
                    if (goldCoin > shortSword.price()) {
                    goldCoin - shortSword.price() ;
                    cout << endl << "You have purchased a sword for " << shortSword.price() << " gold" << endl;
                    }
                    else
                    cout << endl << "I'm sorry, you can't afford this item" << endl;

in the shopEnter function is there a way to use (playerInput == itemName) from invItem instead of having to write a separate if statement for each item in the shop?
Yes, but you should store your items in a more generic container. For example this:

invItem shortSword (3,9,3,"shortsword");

Is "bad" because you're giving a unique variable name to each item. Instead of doing that, you should put all items in a generic container like an array or a vector:

1
2
3
4
5
invItem items[num_items] = {
    invItem(3,9,3,"shortsword"),
    invItem(4,12,5,"longsword"),
    //...
};


Once you have all items in a common container... you can iterate over all of them with a loop:

1
2
3
4
5
for(int i = 0; i < num_items; ++i)
{
    if( playerInput == items[i].getName() )
    {
        //... 




EDIT:

In the future... an even better way to store fixed information like item properties is in external files. Then at startup you can load the files and build that 'items' container dynamically. This will allow you to make changes to item properties and/or add/remove items without having to recompile.
Last edited on
What exactly are you trying to achieve?

invItem is a class - it has no state that you can query or compare with.
Last edited on
max damage is less than min damage?
Thanks for the reply disch, I now have it working and not taking up 100000 lines of if statements
Topic archived. No new replies allowed.