// example of an abstract class called shape with a pure virtual function // called area and with three subclasses that implement specific shapes // (square, rectangle, and circle). We also introduce a comparison function // that allows us to sort a vector of shape objects from smaller to larger // area. #include #include #include #include using namespace std; class shape { public: shape(const string & type) : type(type) { // nothing else to do } virtual double area() const = 0; void print(ostream & out) const { out << type << " of area " << area(); } virtual ~shape() { // nothing else to do } private: string type; }; class square : public shape { public: square(double length) : shape("square"), length(length) { length = length; } double area() const { return length * length; } private: double length; }; class rectangle : public shape { public: rectangle(double length, double width) : shape("rectangle"), length(length), width(width) { // nothing else to do } double area() const { return length * width; } private: double length; double width; }; class circle : public shape { public: circle(double radius) : shape("circle"), radius(radius) { // nothing else to do } double area() const { return 3.14 * radius * radius; } private: double radius; }; ostream & operator<<(ostream & out, const shape & s) { s.print(out); return out; } bool compare(shape * lhs, shape * rhs) { return lhs->area() < rhs->area(); } int main() { vector shapes {new square(12), new rectangle(15, 3.2), new circle(8.4), new circle(1.5), new square(8.7), new rectangle(7.2, 3.2), new square(2.4), new circle(3.7), new circle(7.9)}; for (auto s : shapes) { cout << *s << endl; } cout << endl; sort(shapes.begin(), shapes.end(), compare); for (auto s : shapes) { cout << *s << endl; } cout << endl; for (auto p : shapes) { delete p; } return 0; }