#include "barn.hpp"
void addDaisy(Barn& barn) {
Cow daisy{"Daisy", 7};
barn.addCow(daisy);
}
int main() {
Barn jaysPlace{10}; // Create a barn room for 10 cows
jaysPlace.addCow("Bessie", 3);
jaysPlace.addCow("Mable", 4);
jaysPlace.feed(); // Feed all the cows in the barn
addDaisy(jaysPlace); // Add Daisy to the barn
jaysPlace.feed(); // Feed all the cows in the barn again
// Note: This code still has a space leak! All the Cow objects
// created in the addCow() methods are never deleted.
return 0;
}
#ifndef COW_HPP_INCLUDED
#define COW_HPP_INCLUDED
#include <string>
#include <cstddef>
class Cow {
public:
Cow(); // Default constructor
Cow(std::string name, size_t numSpots); // Parameterized constructor
Cow(const Cow& other); // Copy constructor
~Cow(); // Destructor
void feed(); // Feed the cow
// Disable assignment
Cow& operator=(const Cow& rhs) = delete;
private:
std::string name_;
size_t numSpots_;
bool hasBeenFed_;
};
#endif
#include "cow.hpp"
#include <iostream>
using namespace std;
Cow::Cow() : name_{"(unnamed)"}, numSpots_{0}, hasBeenFed_{false} {
cout << "Created Cow " << name_ << " (default constructor)" << endl;
}
Cow::Cow(string name, size_t numSpots)
: name_{name}, numSpots_{numSpots}, hasBeenFed_{false} {
cout << "Created Cow " << name_ << " (parameterized constructor)" << endl;
}
Cow::Cow(const Cow& other)
: name_{"Copy of " + other.name_},
numSpots_{other.numSpots_},
hasBeenFed_{other.hasBeenFed_} {
cout << "Created Cow " << name_ << " (copy constructor)" << endl;
}
Cow::~Cow() {
cout << "Destroyed Cow " << name_ << endl;
}
void Cow::feed() {
hasBeenFed_ = true;
cout << "Fed Cow " << name_ << endl;
}
#ifndef BARN_HPP_INCLUDED
#define BARN_HPP_INCLUDED
#include <cstddef>
#include <string>
#include "cow.hpp"
class Barn {
public:
Barn(size_t numCows);
void feed();
void addCow(std::string cowName, size_t numSpots);
void addCow(const Cow& cow);
// Disable default constructor, copying and assignment
Barn() = delete;
Barn(const Barn& other) = delete;
Barn& operator=(const Barn& rhs) = delete;
private:
size_t cowCapacity_; // The number of Cows the Barn can hold
size_t cowCount_; // The number of Cows in the Barn
Cow** residentCows_; // Points to an array of Cow*s on the heap
};
#endif
#include "barn.hpp"
#include "cow.hpp"
#include <iostream>
#include <utility>
#include <string>
#include <stdexcept>
Barn::Barn(size_t numCows)
: cowCapacity_{numCows},
cowCount_{0},
residentCows_{new Cow*[cowCapacity_]}
{
// Nothing (else) to do here!
}
void Barn::addCow(std::string cowName, size_t numSpots) {
if (cowCount_ >= cowCapacity_) {
throw std::length_error("Barn is full!");
}
residentCows_[cowCount_] = new Cow{cowName, numSpots};
++cowCount_;
}
void Barn::addCow(const Cow& existingCow) {
if (cowCount_ >= cowCapacity_) {
throw std::length_error("Barn is full!");
}
residentCows_[cowCount_] = new Cow{existingCow};
++cowCount_;
}
void Barn::feed() {
for (size_t i = 0; i < cowCount_; ++i) {
residentCows_[i]->feed();
}
}