Skip to content

Module 05 Solutions

Download Module 05 Solutions

Nested exception classes.

Bureaucrat.hpp
class Bureaucrat {
private:
const std::string _name;
int _grade; // 1 (highest) to 150 (lowest)
public:
class GradeTooHighException : public std::exception {
public:
const char* what() const throw() {
return "Grade is too high!";
}
};
class GradeTooLowException : public std::exception {
public:
const char* what() const throw() {
return "Grade is too low!";
}
};
Bureaucrat(const std::string& name, int grade);
// ... OCF ...
void incrementGrade(); // Throws if would go below 1
void decrementGrade(); // Throws if would go above 150
};
Bureaucrat.cpp
Bureaucrat::Bureaucrat(const std::string& name, int grade)
: _name(name), _grade(grade)
{
if (grade < 1)
throw GradeTooHighException();
if (grade > 150)
throw GradeTooLowException();
}
void Bureaucrat::incrementGrade() {
if (_grade - 1 < 1)
throw GradeTooHighException();
_grade--;
}

Concrete form classes inherit from AForm.

AForm.hpp
class AForm {
protected:
const std::string _name;
bool _signed;
const int _gradeToSign;
const int _gradeToExecute;
public:
virtual void execute(Bureaucrat const& executor) const = 0;
class FormNotSignedException : public std::exception {
const char* what() const throw() { return "Form not signed!"; }
};
};
ShrubberyCreationForm.cpp
void ShrubberyCreationForm::execute(Bureaucrat const& executor) const {
if (!_signed)
throw FormNotSignedException();
if (executor.getGrade() > _gradeToExecute)
throw GradeTooLowException();
std::ofstream file((_target + "_shrubbery").c_str());
file << " _-_" << std::endl;
file << " /~~ ~~\\" << std::endl;
// ... ASCII tree ...
file.close();
}

Function pointers to avoid if/else chains.

Intern.cpp
typedef AForm* (*FormCreator)(const std::string&);
static AForm* createShrubbery(const std::string& target) {
return new ShrubberyCreationForm(target);
}
static AForm* createRobotomy(const std::string& target) {
return new RobotomyRequestForm(target);
}
static AForm* createPresidential(const std::string& target) {
return new PresidentialPardonForm(target);
}
AForm* Intern::makeForm(const std::string& name, const std::string& target) {
std::string names[] = {
"shrubbery creation",
"robotomy request",
"presidential pardon"
};
FormCreator creators[] = {
createShrubbery,
createRobotomy,
createPresidential
};
for (int i = 0; i < 3; i++) {
if (name == names[i]) {
std::cout << "Intern creates " << name << std::endl;
return creators[i](target);
}
}
std::cerr << "Form not found: " << name << std::endl;
return NULL;
}