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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
|
#ifndef Vessel_hpp
#define Vessel_hpp
class Vessel
{
public:
virtual ~Vessel() = default; //as always a virtual destructor
virtual double volume() = 0;
};
#endif /* Vessel_hpp */
#ifndef Box_hpp
#define Box_hpp
#include "Vessel.hpp"
class Box : public Vessel
{
protected:
double length {1.0};
double width {1.0};
double height {1.0};
public:
Box() = default;
Box(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv} {}
double volume() const
{
return length * width * height;
}
};
#endif /* Box_hpp */
#ifndef Can_hpp
#define Can_hpp
#include "Vessel.hpp"
// A macro defining the mathematical constant p
#define PI 3.141592653589793238462643383279502884
class Can : public Vessel
{
protected:
double diameter {1.0};
double height {1.0};
public:
Can(double d, double h) : diameter {d}, height {h} {}
double volume() const
{
return PI * diameter * diameter * height / 4.0;
}
};
#endif /* Can_hpp */
#ifndef Carton_hpp
#define Carton_hpp
#include <string>
#include <string_view>
#include "Box.hpp"
class Carton : public Box
{
private:
std::string material;
public:
// Constructor explicitly calling the base constructor
Carton(double lv, double wv, double hv, std::string_view str)
: Box {lv, wv, hv}, material {str}
{
}
// Function to calculate the volume of a Carton object
double volume() const
{
double vol {(length - 0.5)*(width - 0.5)*(height - 0.5)};
return vol > 0.0? vol : 0.0;
}
};
#endif /* Carton_hpp */
#ifndef ToughPack_hpp
#define ToughPack_hpp
#include "Box.hpp"
class ToughPack : public Box
{
public:
//constructor
ToughPack(double lv, double wv, double hv) : Box {lv, wv, hv} {}
// Function to calculate volume of a ToughPack allowing 15% for packing
double volume() const
{
return 0.85 * Box::volume();
}
};
#endif /* ToughPack_hpp */
/ main.cpp
// Ex14_11
//
// Created by James Farrow on 10/03/2020.
// Copyright © 2020 James Farrow. All rights reserved.
//
// Using an interface class and indirect base classes
#include <iostream>
#include <vector> // For the vector container
#include "Box.hpp" // For the Box class
#include "ToughPack.hpp" // For the ToughPack class
#include "Carton.hpp" // For the Carton class
#include "Can.hpp" // for the Can class
int main(int argc, const char * argv[]) {
Box box{40, 30, 20};
Can can{10, 3};
Carton carton{40, 30, 20, "Plastic"};
ToughPack hardcase{40, 30, 20};
std::vector<Vessel*> vessels {&box, &can, &carton, &hardcase};
for (auto* vessel : vessels)
{
std::cout << "Volume is " << vessel->volume() << std::endl;
}
return 0;
}
|