Classes
Creating custom classes
Pizza.h
#ifndef PIZZA_H
#define PIZZA_H
#include <vector>
#include <string>
using namespace std;
class Pizza {
public:
// constructor
Pizza(string name, int cost, int diameter);
// Member functions
void addTopping(string topping);
// Getters
int getCost() const;
int getDiameter() const;
// Printout
void printToppings() const;
void printPizza() const;
private:
string name;
int cost = 0;
int diameter = 0;
vector<string> toppings{};
};
#endif
Pizza.cpp
#include <iostream>
#include "Pizza.h"
using namespace std;
// constructor
Pizza::Pizza(string name, int cost, int diameter) {
this->name = name;
this->cost = cost;
this->diameter = diameter;
this->toppings.push_back("Cheese");
}
// Member functions
void Pizza::addTopping(string topping) {
bool toppingAlreadyIncluded = false;
for (auto t : toppings)
{
if (topping == t)
{
toppingAlreadyIncluded = true;
cout << "Error: " << topping << " is already on this pizza! (" << name << ")" << endl;
}
}
if (toppingAlreadyIncluded)
{
// do not add the topping
}
else {
toppings.push_back(topping);
}
}
// Getters
int Pizza::getCost() const
{
return cost;
}
int Pizza::getDiameter() const
{
return diameter;
}
// Printout
void Pizza::printToppings() const {
for (auto t : toppings) {
cout << '\t' << t << endl;
}
}
void Pizza::printPizza() const {
cout << "Name: " << name << endl;
cout << "Diameter: " << diameter << "cm"<< endl;
cout << "Cost: €" << cost << endl;
cout << "Toppings: " << endl;
printToppings();
cout << endl;
}
main.cpp
// Project 06-02
// Name: A Pizze Class
#include <iostream>
#include "Pizza.h"
using namespace std;
int main() {
Pizza cheesePizza("Cheese pizza", 25, 6);
Pizza pepperoniPizza("Pepperoni pizza", 33, 11);
pepperoniPizza.addTopping("pepperoni");
Pizza theSpecialPizza("The Special Pizza", 35, 15);
theSpecialPizza.addTopping("pepperoni");
theSpecialPizza.addTopping("black olives");
theSpecialPizza.addTopping("onions");
theSpecialPizza.addTopping("mushroom");
theSpecialPizza.addTopping("mushroom");
cheesePizza.printPizza();
pepperoniPizza.printPizza();
theSpecialPizza.printPizza();
return 0;
}