aboutsummaryrefslogtreecommitdiff
path: root/week11/Exercise07/DynamicArray.hpp
blob: b7d8fb71a8114b834a8060ff8b7ce60223d6d718 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#pragma once

template <class T>
class DynamicArray {
	void free();
	void copyFrom(const DynamicArray& other);

protected:
	T* elems;
	unsigned allocated;
	unsigned size;

public:
	DynamicArray();
	virtual ~DynamicArray();
	DynamicArray(const DynamicArray& other);
	DynamicArray& operator=(const DynamicArray& other);
	DynamicArray(DynamicArray&& other);
	DynamicArray& operator=(DynamicArray&& other);

	virtual T& operator[](int index) = 0;
	virtual const T& operator[](int index) const = 0;
	// Отговорът е не, не можем да използваме оператор += в полморфна йерархия
	// Понеже String и Numbers не са шаблонни, а използват конкретна "инстанция" на шаблонния клас
	// тогава полиморфно += би означавало += между разногласни типове, което няма как да стане (добре).
	virtual DynamicArray& operator+=(const DynamicArray& other) = 0;
};

template <class T>
void DynamicArray<T>::free() {
	delete[] elems;
}

template <class T>
void DynamicArray<T>::copyFrom(const DynamicArray& other) {
	this->size = other.size;
	this->allocated = other.allocated;
	elems = new T[allocated];
	for (int i = 0; i < size; i++) {
		elems[i] = other.elems[i];
	}
}

template <class T>
DynamicArray<T>::DynamicArray() {
	elems = nullptr;
	size = allocated = 0;
}

template <class T>
DynamicArray<T>::~DynamicArray() {
	free();
}

template <class T>
DynamicArray<T>::DynamicArray(const DynamicArray& other) {
	copyFrom(other);
}

template <class T>
DynamicArray<T>& DynamicArray<T>::operator=(const DynamicArray& other) {
	if (this != &other) {
		free();
		copyFrom(other);
	}
	return *this;
}

template <class T>
DynamicArray<T>::DynamicArray(DynamicArray&& other) {
	this->elems = other.elems;
	other.elems = nullptr;
	this->second = other.second;
	other.second = nullptr;
	this->allocated = other.allocated;
	this->size = other.size;
}

template <class T>
DynamicArray<T>& DynamicArray<T>::operator=(DynamicArray&& other) {
	if (this != &other) {
		free();

		this->elems = other.elems;
		other.elems = nullptr;
		this->allocated = other.allocated;
		this->size = other.size;
	}
	return *this;
}