Reputation: 67
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);
};
Upvotes: 0
Views: 83
Reputation: 11779
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.
Upvotes: 1