I've built a class for an e-commerce Item
, and the ShoppingCart
class for checkout functions.
The thing I'm most concerned about is my use of pointers. I think I've used them properly in this situation, but I could be wrong.
Item.hpp
#ifndef Item_hpp
#define Item_hpp
#include <iostream>
using namespace std;
class Item {
private:
string name;
double price;
int quantity;
public:
void setName(string);
void setPrice(double);
void setQuantity(int);
string getName();
double getPrice();
int getQuantity();
// Constructors
Item();
Item(string, double, int);
};
#endif
Item.cpp
#include "Item.hpp"
#include <iostream>
using namespace std;
Item::Item() {
name = "";
price = 0.0;
quantity = 0;
}
Item::Item(string itemName, double itemPrice, int itemQuantity) {
setName(itemName);
setPrice(itemPrice);
setQuantity(itemQuantity);
}
void Item::setName(string itemName) {
name = itemName;
}
void Item::setPrice(double itemPrice) {
price = itemPrice;
}
void Item::setQuantity(int itemQuantity) {
quantity = itemQuantity;
}
string Item::getName() {
return name;
}
double Item::getPrice() {
return price;
}
int Item::getQuantity() {
return quantity;
}
ShoppingCart.hpp
#ifndef ShoppingCart_hpp
#define ShoppingCart_hpp
#include "Item.hpp"
#include <iostream>
using namespace std;
class ShoppingCart {
private:
Item* itemArray[100];
int arrayEnd;
public:
void addItem(Item *);
double totalPrice();
// Constructors
ShoppingCart();
};
#endif
ShoppingCart.cpp
#include "ShoppingCart.hpp"
#include "Item.hpp"
#include <iostream>
using namespace std;
ShoppingCart::ShoppingCart() {
for (int i=0; i<100; i++) {
itemArray[i] = {NULL};
}
arrayEnd = 0;
}
void ShoppingCart::addItem(Item *currentItem) {
itemArray[arrayEnd] = currentItem;
arrayEnd++;
}
double ShoppingCart::totalPrice() {
double totalPrice;
for (int i=0; i<100; i++) {
if (itemArray[i] != NULL) {
totalPrice += itemArray[i]->getPrice() * itemArray[i]->getQuantity();
} else {
break;
}
}
return totalPrice;
}