C++ Programming - Practical 8

Exercise 1

Consider the base class shape,

shape.h

#ifndef shape_h #define shape_h #include <string> class shape { public: virtual double area() = 0; virtual double perimeter() = 0; void describe(); virtual std::string name(); protected: std::string color; }; #endif

shape.cpp

#include "shape.h" #include <iostream> using namespace std; void shape::describe() { cout << "The " << color << " " << name() << " has an area of " << area() << " and a perimeter of " << perimeter() << endl; } string shape::name() { return("shape"); }

Note that here the virtual functions area() and perimeter() are declared =0 to indicate they have no implementation in the base class. A derived class for a rectangle might be as follows,

rectangle.h

#ifndef rectangle_h #define rectangle_h #include "shape.h" class rectangle : public shape { public: rectangle(std::string color, double width, double height); double area(); double perimeter(); std::string name(); private: double width; double height; }; #endif

rectangle.cpp

#include "rectangle.h" #include <iostream> using namespace std; rectangle::rectangle(string c, double w, double h) { color=c; width=w; height=h; } double rectangle::area() { return(width*height); } double rectangle::perimeter() { return(2*width+2*height); } string rectangle::name() { return("rectangle"); }

and finally the test program,

test.cpp

#include "rectangle.h" #include <vector> int main() { std::vector<shape*> shapes; rectangle r1("green", 10, 4); rectangle r2("red", 5, 8); shapes.push_back(&r1); shapes.push_back(&r2); for(int i=0; i<shapes.size(); i++) shapes[i]->describe(); return 0; }

Exercise 2