using namespace std; #include #include // Modern C++ version, requires g++ -std=c++14 #include using namespace std; class shape { // abstract class because of pure virtual functions protected: int x; int y; public: shape(int x0, int y0): x{x0},y{y0} {} virtual double distance(shape& other) { // should this be "virtual"? int dx = x-other.x, dy = y-other.y; return sqrt(dx*dx + dy*dy); } virtual double area()= 0; // "pure virtual" (aka "abstract") virtual double circumference() = 0; }; class circle : public shape { // public inheritance = "is a" protected: double radius; public: circle(int a, int b, double r) : shape(a,b) {radius=r;} double area() override { return M_PI*radius*radius; } // note "override" double circumference() override {return M_PI*radius*2;} double get_radius() { return radius; } // extra function }; class rectangle : public shape { protected: double width; double height; public: rectangle(int a, int b, double w, double h): shape(a,b) {width=w; height=h;} double area() override { return width*height; } double circumference() override {return width*2 + height*2; } }; class square : public rectangle { // rectangle with same width as height public: square(int x, int y, double w) : rectangle(x,y,w,w) {} }; int main() { unique_ptr S[4]; S[0] = make_unique(4,5,8); S[1] = make_unique(7,9,5,10); S[2] = make_unique(5,6,9); char x; cout << "you want a circle or something else? "; cin >> x; if (x=='c' || x=='y') S[3] = make_unique(10,10,10); else S[3] = make_unique(10,10,10); for(auto& s:S) cout << s->area() << endl; for(auto& s:S) cout << s->circumference() << endl; // static type casting in C++ is not safe: double r = ((circle&)*S[1]).get_radius(); // compiles but what did you get? cout << "radius of circe S[1] is " << r << endl; // dynamic type casting, like in Java: double rad = (dynamic_cast(*S[1])).get_radius(); //compiles, // but results in RUNTIME type-casting exception }//main