aboutsummaryrefslogtreecommitdiff
path: root/week04/Exercise4.cpp
diff options
context:
space:
mode:
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;
+}