0

I am writing a program for a shopping cart. Everything is derived from the customer. Every customer has a shopping cart. Therefore I thought to put the shopping cart before the Customer class. When doing this I can't declare Shopping cart as a child of Customer. Any fixes?

class ShoppingCart : public Customer
{
    private:
    Item* cart[MAX_SIZE] = {NULL};  //problem  may occur
    int size;

    public:
    void addItem(char* type, char* title, char* description, double price);
    void showCart();
};

class Customer
{
    private:
    int ID, items;
    char* firstName, *lastName;
    ShoppingCart* Cart;

    public:
    Customer(char* userFirst, char* userLast, int userID, ShoppingCart* cart)
    {
        this->ID = userID;
        this->firstName = userFirst;
        this->lastName = userLast;
        this->Cart = cart;
    }
    friend void ShoppingCart::addItem(char* type, char* title, char* description, double price);
};
MaxAttax
  • 67
  • 6

1 Answers1

1

As for your problem, no, there is no solution to the problem other than declaring and defining the base class before the derived class. Forward declaration would not work here (As I naively thought), since the child class needs contextual information from the base class.

While the above may work, I would like to point out that you really aren't understanding inheritance. Inheritance is based off a is a relationship i.e Derived is a Base, not a has a relationship, which is what your code is trying to emulate. If you want to emulate a has a relationship, then you should make the class ShoppingCart a member of Customer, since that will show that each Customer has a shopping cart. Inheritance is not the right method to solve your problem here.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • Is there any way I could make the shopping cart aware of the of the private member variables in customer – MaxAttax Jan 31 '18 at 22:32
  • 1
    Yes, make `ShoppingCart` a [`friend`](http://en.cppreference.com/w/cpp/language/friend) of `Customer`. – Arnav Borborah Jan 31 '18 at 22:34
  • I would highly advise against the use of `friend` here as that breaks encapsulation when setters and getters would work just fine. `friend` should be reserved for special cases like `operator<<` and when you need to write unit tests. – scohe001 Feb 01 '18 at 00:17
  • On the other hand, `public` accessor functions can globally weaken or break encapsulation, while `friend` restricts that break to only trusted classes and functions. In this case I agree though. Add `removeItem` and `checkout` methods and all the accessibility anyone should need is present in `ShoppingCart`. `ShoppingCart` should be looking after itself, not letting others poke around inside it. – user4581301 Feb 01 '18 at 00:35