-1

I have multiple files for each class. I'm trying to use data from a struct (inside the first class) and use it in the second class.

I've tried putting the struct in its own file, but this felt a bit unnecessary. I've tried a few different ways of coding it out, such as declaring the struct in main and also declaring the struct in the other class.

// class 1
class Shop
{
  public:
    struct Products
    {
      int price;
      int quantity;
    };
   void SetProductValue();
  private:
    float register_total; 
};
// class 2:
class Consumer 
{
  public:
    Shop Products; 
    int total_customers;
    bool buy_product(); // <-- 
    for this?
  private:
    string consumer_name;
    float Consumer_balance;
};

What does the function description look like for void buy_product()?

bool Consumer::buy_product();
{
  if (consumer_balance < Products.price) return false;
  if (consumer_balance >= Products.price) return true;
}

This is one of several ways I've tried, and I get errors for trying to do Products.price

Quixote
  • 1
  • 1

1 Answers1

1

struct Products { ... }; declares a type, not a product instance.

In order to have an actual product in your class, you have to declare a member variable:

class Shop
{
  public:
    struct Product // no need for "s"
    {
      int price;
      int quantity;
    };
   void SetProductValue();
  private:
    // either:
    Product product; // <--- HERE

    // or, if your shop has multiple products:
    std::vector<Product> products;

    float register_total; 
};

In order to access one specific product (which one?), your Shop class has to expose some accessor functions. An option is to select a product by name:

Product Shop::GetProductByName(const std::string& name) const
{
    // find right product _instance_ here
}
TheOperator
  • 5,936
  • 29
  • 42
  • I wasn't declaring a member variable, that fixed some issues. But when I go to write the definition it still says that Product "does not name a type." ```cpp Product Shop::GetProductByName(const string &name) const { product_name = name; // find product name and output. return name; } ``` – Quixote May 05 '19 at 21:12
  • It is declared in the scope of `Shop`, so you need to qualify it accordingly: `Shop::Product`. – TheOperator May 05 '19 at 21:20