Website Summary Files Commits Branches @commit @diff @stats
path: root / Polymorphism / Farm(cloneFunction)
diff options
context:
space:
mode:
Commit48bf3ddb69755e32a5741033aad9e3bc1556f488 (patch)
Author
 Angeld55 <achi_d@abv.bg>
2019-09-20 14:31:19 +0300
Committer
 GitHub <noreply@github.com>
2019-09-20 14:31:19 +0300
Files460efb462bf8473005292b8f59ddb2572babb680 /Polymorphism/Farm(cloneFunction)
Object-oriented_programming_FMI-48bf3ddb69755e32a5741033aad9e3bc1556f488.tar
Object-oriented_programming_FMI-48bf3ddb69755e32a5741033aad9e3bc1556f488.tar.gz
Object-oriented_programming_FMI-48bf3ddb69755e32a5741033aad9e3bc1556f488.zip
Parenteffe5e09e035eae3b7ea6ce30db91dd4e7f93895 (diff)
Rename Polymorphism/Figures/Farm(cloneFunction)/Farm.hpp to Polymorphism/Farm(cloneFunction)/Farm.hpp
1 files changed, 98 insertions, 0 deletions
-rw-r--r--Polymorphism/Farm(cloneFunction)/Farm.hpp98
diff --git a/Polymorphism/Farm(cloneFunction)/Farm.hpp b/Polymorphism/Farm(cloneFunction)/Farm.hpp
new file mode 100644
index 0000000..5dc7cc8
--- /dev/null
+++ b/Polymorphism/Farm(cloneFunction)/Farm.hpp
@@ -0,0 +1,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;
+}