Website Summary Files Commits Branches @commit @diff @stats
path: root / Week10 / Exercise03 / Shop.cpp
diff options
context:
space:
mode:
Commit7546f0d0da487e16f0a8671c09a46e1cee2bc03a (patch)
Author
 Syndamia <kamen@syndamia.com>
2026-05-02 14:57:36 +0300
Committer
 Syndamia <kamen@syndamia.com>
2026-05-02 14:57:36 +0300
Files6462868cebe114a87ca38252af9a49bce6603286 /Week10/Exercise03/Shop.cpp
oop-2025-solutions-7546f0d0da487e16f0a8671c09a46e1cee2bc03a.tar
oop-2025-solutions-7546f0d0da487e16f0a8671c09a46e1cee2bc03a.tar.gz
oop-2025-solutions-7546f0d0da487e16f0a8671c09a46e1cee2bc03a.zip
Parentc98c633b7087e3c52f4b05236f3509a9ec5f2bba (diff)
feat(Week10): Add solutions
1 files changed, 91 insertions, 0 deletions
-rw-r--r--Week10/Exercise03/Shop.cpp91
diff --git a/Week10/Exercise03/Shop.cpp b/Week10/Exercise03/Shop.cpp
new file mode 100644
index 0000000..4ed8ce3
--- /dev/null
+++ b/Week10/Exercise03/Shop.cpp
@@ -0,0 +1,91 @@
+#include "Shop.h"
+#include <cstring>
+#include <utility>
+
+void Shop::free() {
+ delete[] sales;
+}
+
+void Shop::copyFrom(const Shop& other) {
+ salesAlloc = other.salesAlloc;
+ salesCount = other.salesCount;
+
+ sales = new Sale[salesAlloc];
+ for (unsigned i = 0; i < salesCount; ++i)
+ sales[i] = other.sales[i];
+}
+
+void Shop::resize() {
+ salesAlloc = salesAlloc == 0 ? 8 : salesAlloc * 2;
+ Sale* salesLarger = new Sale[salesAlloc];
+
+ for (unsigned i = 0; i < salesCount; ++i)
+ salesLarger[i] = sales[i];
+
+ delete[] sales;
+ sales = salesLarger;
+}
+
+Shop::Shop() : Inventory(), sales(), salesCount(), salesAlloc()
+{ }
+
+Shop::~Shop() {
+ free();
+}
+
+Shop::Shop(const Shop& other) : Inventory(other) {
+ copyFrom(other);
+}
+
+Shop& Shop::operator=(const Shop& other) {
+ if (this != &other) {
+ Inventory::operator=(other);
+ free();
+ copyFrom(other);
+ }
+ return *this;
+}
+
+Shop::Shop(Shop&& other) : Inventory(std::move(other)) {
+ sales = other.sales;
+ salesCount = other.salesCount;
+ salesAlloc = other.salesAlloc;
+
+ other.sales = nullptr;
+ other.salesAlloc = other.salesCount = 0;
+}
+
+Shop& Shop::operator=(Shop&& other) {
+ if (this != &other) {
+ Shop::operator=(std::move(other));
+
+ free();
+
+ sales = other.sales;
+ salesCount = other.salesCount;
+ salesAlloc = other.salesAlloc;
+
+ other.sales = nullptr;
+ other.salesAlloc = other.salesCount = 0;
+ }
+ return *this;
+}
+
+bool Shop::Purchase(const Sale& sale) {
+ unsigned productIndex = 0;
+ while (productIndex < productsCount &&
+ strcmp(sale.productName, products[productIndex].name) != 0)
+ {
+ ++productIndex;
+ }
+
+ if (productIndex == productsCount || products[productIndex].quantity >= sale.quantity)
+ return false;
+
+ if (salesCount >= salesAlloc)
+ resize();
+ sales[salesCount++] = sale;
+
+ products[productIndex].quantity -= sale.quantity;
+ return true;
+}