/******************************************************* Object Oriented Programming (OOP) in C++ Author: Francesco Taurisano This script can be compiled using DEV-C++ IDE. Topics: How to create a class Attributes and methods of a class Derived class Polymorphism Constructor and destructor *******************************************************/ #include #include using namespace std; // Defining a class class rectangle { public: // Attributes of the class int base, height; // Method of the class int area() { return base*height; } }; // Defining a derived class from class rectangle class rectangle2 : public rectangle { public: // Defining a new method for the derived class int perimeter() { return (base+height)*2; } }; // Defining another derived class from class rectangle // Polymorphism, constructor and destructor class right_triangle : public rectangle { private: // Defining a new method for the derived class right_triangle float hypotenuse() { return sqrt(pow(float(base),2)+pow(float(height),2)); } public: // Defining the method perimeter float perimeter() { return (base+height+hypotenuse()); } // Redefining the method area (polymorphism) float area() { return (float(rectangle::area())/2); } // Constructor right_triangle() { base=0; height=0; cout << "The object has been initialized." << endl; } // Destructor ~right_triangle() { cout << "Object has been removed." << endl; } }; int main() { rectangle shape1; rectangle2 shape2; right_triangle shape3; // Shape1 - Input cout << "Shape1 (rectangle). Enter base: "; cin >> shape1.base; cout << "Shape1 (rectangle). Enter height: "; cin >> shape1.height; // Shape2 - Input cout << "Shape2 (rectangle). Enter base: "; cin >> shape2.base; cout << "Shape2 (rectangle). Enter height: "; cin >> shape2.height; // Shape3 - Input cout << "Shape3 (right triangle). Enter base: "; cin >> shape3.base; cout << "Shape3 (right triangle). Enter height: "; cin >> shape3.height; cout << endl; // Shape1 - Output cout << "Shape1. Rectangle area = " << shape1.area() << endl << endl; // Shape2 - Output cout << "Shape2. Rectangle area = " << shape2.area() << endl; cout << "Shape2. Rectangle perimeter = " << shape2.perimeter() << endl << endl; // Shape3 - Output cout << "Shape3. Right triangle area = " << shape3.area() << endl; cout << "Shape3. Right triangle perimeter = " << shape3.perimeter() << endl; system("pause"); return 0; }