Thread: How to use class object in other class

  1. #1
    Registered User
    Join Date
    Feb 2015
    Posts
    56

    How to use class object in other class

    I have some classes and i'm trying to use an Item object in the Shop, I need to setup the items that can be sold but VS keeps giving me errors.

    Code:
    #include "pch.h"#include <iostream>
    #include <string>
    #include <map>
    
    
    class Item
    {
        public:
            Item(std::string itemName, int itemBaseValue)
                :    mItemName(itemName), mItemBaseValue(itemBaseValue){}
    
    
        protected:
            std::string mItemName;
    
    
            int mItemBaseValue;
    };
    
    
    class Player
    {
        public:
            std::string GetPlayerName() const
            {
                return mPlayerName;
            }
            int GetPlayerCredits() const
            {
                return mPlayerCredits;
            }
    
    
        private:
            std::string mPlayerName;
    
    
            std::pair<std::string, int> mPlayerAttackNameAndPower;
            std::map<std::string, int> mPlayerInventory;
    
    
            int mPlayerCredits; //Money
    };
    
    
    class Enemy
    {
        public:
            Enemy(std::string enemyName, std::string enemyType, std::pair<std::string, int> enemyAttackNameAndPower)
                :    mEnemyName(enemyName), mEnemyType(enemyType), mEnemyAttackNameAndPower(enemyAttackNameAndPower){}
            void GetEnemyName();
    
    
        private:
            std::string mEnemyName;
            std::string mEnemyType;
    
    
            std::pair<std::string, int> mEnemyAttackNameAndPower;
    };
    
    
    class Shop : public Item
    {
        public:
            void CallShop(Item& itemName);
            void CheckPlayerCreditBalance();
            void ProcessTransaction(){}
    
    
        private:
    
    
    };
    
    
    void Shop::CheckPlayerCreditBalance()
    {
        Player player;
    
    
        if (player.GetPlayerCredits() >= mItemBaseValue)
        {
            ProcessTransaction();
        }
        else if (player.GetPlayerCredits() < mItemBaseValue)
        {
            std::cout << "You do not posess the credits required to purchase this item, you have:\n";
            std::cout << player.GetPlayerCredits() << " and you need: " << player.GetPlayerCredits() - mItemBaseValue << " credits to purchase this item!\n";
        }
    }
    
    
    void Shop::CallShop()
    {
        Item MedKit("Med Kit", 50);
    
    
        std::cout << "Welcome to the shop, what would you like to buy?\n";
        std::cout << "1) Med-Kit" << MedKit.mItemName << " C" << MedKit.mItemBaseValue << "\n";
    
    
    }
    
    
    int main()
    {
    
    
        return 0;
    }

    Errors:


    Severity Code Description Project File Line Suppression State
    Error (active) E0410 protected member "Item::mItemBaseValue" (declared at line 15) is not accessible through a "Item" pointer or object Dino Arena C:\Users\Chay\Desktop\Work\C++\Visual Studio Projects\Dino Arena\Dino Arena\Dino Arena.cpp 84
    Error (active) E0410 protected member "Item::mItemName" (declared at line 13) is not accessible through a "Item" pointer or object Dino Arena C:\Users\Chay\Desktop\Work\C++\Visual Studio Projects\Dino Arena\Dino Arena\Dino Arena.cpp 84
    Error C2248 'Item::mItemName': cannot access protected member declared in class 'Item' Dino Arena c:\users\chay\desktop\work\c++\visual studio projects\dino arena\dino arena\dino arena.cpp 84
    Error C2248 'Item::mItemBaseValue': cannot access protected member declared in class 'Item' Dino Arena c:\users\chay\desktop\work\c++\visual studio projects\dino arena\dino arena\dino arena.cpp 84
    Last edited by CH1156; 08-29-2018 at 10:52 AM.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    It doesn't make sense for Shop to inherit from Item. A shop is not an item. A shop would normally contain items.


    Your code is not fleshed out enough to make sense of. You say that CallShop takes an Item reference in the class declaration but you don't have such a reference in the function definition. CheckPlayerCreditBalance is trying to access some unknown Item's mItemBaseValue where there is no item (and the member is protected anyway).


    And you should probably respond to previous responses or people will probably stop helping you.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Feb 2015
    Posts
    56
    So how would I make this work? I mean some parts of the classes have to interact, I need to be able to check if the player has enough credits to buy an item, so I need to compare players credits to the items base value right? but the way it is I cant do that, whats the best, or most common way of doing that? or is my approach wrong altogether?

    Code:
    You say that CallShop takes an Item reference in the class declaration but you don't have such a reference in the function definition. CheckPlayerCreditBalance is trying to access some unknown Item's mItemBaseValue where there is no item (and the member is protected anyway).
    Thats actually a remnant of something I was trying to do before, I just forgot to take it out.
    Last edited by CH1156; 08-29-2018 at 06:43 PM.

  4. #4
    Registered User
    Join Date
    Feb 2015
    Posts
    56
    I could make a Vendor class, since a Vendor has both a shop and items, I could inherit these things from that, but what if I had a class that was unrelated to another but needed to compare values to another member in it? what do I do then? I find myself needing to do this sometimes, i'm not sure if it's just bad design on my part or a common problem.

  5. #5
    Registered User
    Join Date
    Feb 2015
    Posts
    56
    bump?

  6. #6
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    I think you're misunderstanding inheritance. It is often overused, and if all you mean is that, for instance, a Shop "has" Items, then you should use "composition" instead of inheritance. I.e., the shop should contain a collection of items. Here's a simplistic example.
    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
     
    class Item {
        string name;
        int    price;
    public:
        Item(string name, int price) : name(name), price(price) {}
        friend ostream& operator<<(ostream& os, const Item& item) {
            os << item.name << ' ' << item.price;
            return os;
        }
        int getPrice() const { return price; }
        string getName() const { return name; }
    };
     
    class Player {
        string       name;
        int          credits;
        vector<Item> items;
    public:
        Player(string name, int credits) : name(name), credits(credits) {}
        void showItems() {
            cout << "You have:\n";
            for (int i = 0; i < int(items.size()); i++)
                cout << "  " << items[i] << '\n';
        }
        int getCredits() const { return credits; }
        void addItem(const Item& item) {
            items.push_back(item);
            credits -= item.getPrice();
        }
    };
     
    class Shop {
        vector<Item> items;
    public:
        void addItem(string name, int cost) {
            items.push_back(Item(name, cost));
        }
        void buy(Player& p) {
            cout << "Shop has:\n";
            for (int i = 0; i < int(items.size()); i++)
                cout << "  " << items[i] << '\n';
            string name;
            cout << "What do you want to buy? ";
            getline(cin, name);
            bool found = false;
            for (int i = 0; i < int(items.size()); i++)
                if (items[i].getName() == name) {
                    found = true;
                    if (p.getCredits() < items[i].getPrice())
                        cout << "You can't afford that.\n";
                    else {
                        p.addItem(items[i]);
                        items.erase(items.begin() + i);
                    }
                }
            if (!found)
                cout << "That item isn't in the shop.\n";
        }
    };
     
    int main() {
        Player player("Joe", 1000);
     
        Shop shop;
        shop.addItem("Bucket", 100);
        shop.addItem("Spade", 50);
        shop.addItem("DiamondToilet", 10000);
     
        while (true) {
            shop.buy(player);
            player.showItems();
            string answer;
            cout << "Buy more? ";
            getline(cin, answer);
            if (answer[0] != 'y' && answer[0] != 'Y')
                break;
        }
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  7. #7
    Registered User
    Join Date
    Feb 2015
    Posts
    56
    YES, that is exactly what I wanted to do thank you, I struggled with that for so long! I didnt know there was a name for it. I'll do more research on composition to understand it better and see more examples.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 05-22-2009, 11:12 PM
  2. Base-class pointer, accessing object from derived class
    By Korhedron in forum C++ Programming
    Replies: 15
    Last Post: 09-28-2008, 05:30 AM
  3. Replies: 8
    Last Post: 01-13-2008, 05:57 PM
  4. Replies: 3
    Last Post: 02-12-2002, 10:09 PM

Tags for this Thread