aboutsummaryrefslogtreecommitdiff
path: root/week04/Exercise4.cpp
diff options
context:
space:
mode:
authorSyndamia <kamen@syndamia.com>2024-03-20 13:20:09 +0200
committerSyndamia <kamen@syndamia.com>2024-03-20 13:20:09 +0200
commitcdd5b6c28b12a4763c9b1eef9ba45ca85a6ddaa2 (patch)
treec3dca402c9203b0e06b06574bd6459b3b58d5fbd /week04/Exercise4.cpp
parent6b7a20b652bd3388ceaac60c96479419ac2c4859 (diff)
downloadoop-2023-solutions-cdd5b6c28b12a4763c9b1eef9ba45ca85a6ddaa2.tar
oop-2023-solutions-cdd5b6c28b12a4763c9b1eef9ba45ca85a6ddaa2.tar.gz
oop-2023-solutions-cdd5b6c28b12a4763c9b1eef9ba45ca85a6ddaa2.zip
[w4] Solved exercises 1-5
Diffstat (limited to 'week04/Exercise4.cpp')
-rw-r--r--week04/Exercise4.cpp47
1 files changed, 47 insertions, 0 deletions
diff --git a/week04/Exercise4.cpp b/week04/Exercise4.cpp
new file mode 100644
index 0000000..3716287
--- /dev/null
+++ b/week04/Exercise4.cpp
@@ -0,0 +1,47 @@
+#include <iostream>
+#include <cstring>
+
+struct DynamicString {
+private:
+ char* str;
+ int size;
+
+ void copyFrom(const DynamicString& other) {
+ this->str = new char[other.size + 1];
+ strncpy(this->str, other.str, other.size + 1);
+ this->size = other.size;
+ }
+
+ void free() {
+ delete[] str;
+ }
+
+public:
+ DynamicString(const char* str) {
+ size = strlen(str);
+ this->str = new char[size + 1];
+ strncpy(this->str, str, size + 1);
+ }
+ ~DynamicString() {
+ free();
+ }
+
+ DynamicString& operator=(const DynamicString& other) {
+ if (this != &other) {
+ free();
+ copyFrom(other);
+ }
+ return *this;
+ }
+
+ const char* GetStr() {
+ return str;
+ }
+};
+
+int main() {
+ DynamicString s1("Hello");
+ DynamicString s2("World");
+ s1 = s2;
+ std::cout << s1.GetStr() << std::endl;
+}