aboutsummaryrefslogtreecommitdiff
path: root/week03/Exercise5.cpp
blob: 28721a4ae5c3cc3c8ad40d0831fb7755c82d2594 (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
91
92
93
94
95
96
#include <cstring>

struct Car {
private:
	char* model;
	unsigned int doors;
	unsigned int seats;

public:
	Car() {
		model = nullptr;
		doors = 0;
		seats = 0;
	}
	Car(const char* model, unsigned int doors, unsigned int seats) {
		this->model = nullptr;
		setModel(model);
		setDoors(doors);
		setSeats(seats);
	}
	~Car() {
		delete[] model;
	}

	const char* getModel() {
		return model;
	}
	void setModel(const char* newModel) {
		delete[] model;
		model = new char[strlen(newModel) + 1];
		strcpy(model, newModel);
	}

	unsigned int getDoors() {
		return doors;
	}
	void setDoors(unsigned int newDoorsCount) {
		doors = newDoorsCount;
	}

	unsigned int getSeats() {
		return seats;
	}
	void setSeats(unsigned int newSeatsCount) {
		seats = newSeatsCount;
	}

	void CopyDataTo(Car& destination) {
		destination.setModel(model);
		destination.setDoors(doors);
		destination.setSeats(seats);
	}
};

struct TrafficJam {
private:
	Car* cars;
	int size;
	int lastIndex;

	void resize() {
		Car* newCars = new Car[size * 2];
		for (int i = 0; i < size; i++) {
			cars[i].CopyDataTo(newCars[i]);
		}
		delete[] cars;
		cars = newCars;
		size *= 2;
	}

public:
	TrafficJam() {
		size = 3;
		cars = new Car[size];
		lastIndex = 0;
	}
	~TrafficJam() {
		delete[] cars;
	}

	void AddCar(Car& car) {
		if (lastIndex == size)
			resize();
		car.CopyDataTo(cars[lastIndex++]);
	}
};

int main() {
	TrafficJam tj;

	Car c1("Toyota", 4, 5);
	Car c2("Ferarri", 2, 2);

	tj.AddCar(c1);
	tj.AddCar(c2);
}