Website Summary Files Commits Branches @commit @diff @stats
path: root / Polymorphism / Farm(cloneFunction) / Farm.hpp
blob: 5dc7cc8a63aa09d4a06860be7f0b4edd8603a1bd (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
97
98
#include "Animal.hpp"

// Collection of all animals
class Farm
{
	Animal** animals;
	int len;
	int count;
	void Free();
	void CopyFrom(const Farm& other);
	bool AddAnimal(Animal* an);
public:
	Farm(int len);
	Farm(const Farm& other);
	Farm& operator=(const Farm& other);
	~Farm();
	bool AddCat(std::string name);
	bool AddDog(std::string name);
	bool AddCow(std::string name);
	void RoarAll();
};
Farm::Farm(int len)
{
	animals = new Animal*[len];
	this->len = len;
	count = 0;
}
Farm::Farm(const Farm& other)
{
	CopyFrom(other);
}
Farm& Farm::operator=(const Farm& other)
{
	if (this != &other)
	{
		Free();
		CopyFrom(other);
	}
	return *this;
}
Farm::~Farm()
{
	Free();
}
bool Farm::AddAnimal(Animal* an)
{
	if(count == len)
		return false;
	animals[count++]=c;
	return true;
}
bool Farm::AddCat(std::string name)
{
	Cat* c = new Cat(name);
	if(!AddAnimal(c))
	{
		delete c;
		return false;
	}
}
bool Farm::AddDog(std::string name)
{
	Dog* c = new Dog(name);
	if(!AddAnimal(c))
	{
		delete c;
		return false;
	}
}
bool Farm::AddCow(std::string name)
{
	Cow* c = new Cow(name);
	if(!AddAnimal(c))
	{
		delete c;
		return false;
	}
}
void Farm::RoarAll()
{
	for (int i = 0; i < count; i++)
		animals[i]->Roar();  //roar is a virtual function 
	
}
void Farm::Free()
{
	for (int i = 0; i < count; i++)
		delete animals[i]; //~Animal() is virtual
	delete[] animals;
}
void Farm::CopyFrom(const Farm& other)
{
	animals = new Animal*[other.len];
	for (int i = 0; i < other.count; i++)
		animals[i] = other.animals[i]->clone(); //clone is a virtual function
	len = other.len;
	count = other.count;
}