Summary Files Commits Branches @commit @diff @stats
path: root / Year 1 / Object-oriented Programming / Solutions Sem. 08 / ex3 / DynStr.cpp
blob: a7499a826df54632316370ff861db84399e03293 (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
48
49
50
51
52
53
54
#include "DynStr.h"
#include <cstring>

/* Private */

void DynStr::free() {
	delete[] str;
}

void DynStr::copyFrom(const DynStr& other) {
	length = other.length;

	str = new char[length];
	for (int i = 0; i < length; i++)
		str[i] = other.str[i];
}

/* Public */

DynStr::DynStr() : DynStr("")
{}

DynStr::DynStr(const char* str) {
	int strLen = strlen(str);
	strLen++; // Make space for \0

	this->str = new char[strLen];
	strcpy(this->str, str);
	length = strLen;
}

DynStr::DynStr(const DynStr& copy) {
	copyFrom(copy);
}

DynStr& DynStr::operator=(const DynStr& other) {
	if (this != &other) {
		free();
		copyFrom(other);
	}
	return *this;
}

DynStr::~DynStr() {
	free();
}

const char* DynStr::get_str() const {
	return str;
}

int DynStr::compare(const char* other) const {
	return strcmp(str, other);
}