aboutsummaryrefslogtreecommitdiff
path: root/week04/Exercise4.cpp
blob: 3716287ccd5d94cdc1b32440736b3f69547793c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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;
}