|
| 1 | +// // Extend the above program to display the area of circles. This requires the addition of a new derived class 'circle' that computes the area of a circle. Remember, for a circle we need only one value, its radius, but the get_data() function in the base class requires two values to be passed. (Hint: Make the second argument of get_data() function as a default one with zero value.) |
| 2 | + |
| 3 | +// // Header files |
| 4 | +#include <iostream> |
| 5 | +#include <conio.h> |
| 6 | + |
| 7 | +// // use namespace |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +// // define class Shape |
| 11 | +class Shape |
| 12 | +{ |
| 13 | +protected: |
| 14 | + // // instance member variables |
| 15 | + double d1, d2; |
| 16 | + |
| 17 | +public: |
| 18 | + // instance member function to set data |
| 19 | + void setData(double d1, double d2 = 0) |
| 20 | + { |
| 21 | + this->d1 = d1; |
| 22 | + this->d2 = d2; |
| 23 | + } |
| 24 | + |
| 25 | + // instance member function to display the area |
| 26 | + virtual void displayArea() const |
| 27 | + { |
| 28 | + cout << "\nNot Implemented this for class Shape..."; |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +// // define class Triangle by inheriting class Shape |
| 33 | +class Triangle : public Shape |
| 34 | +{ |
| 35 | +public: |
| 36 | + // instance member function to display the area |
| 37 | + void displayArea() const override |
| 38 | + { |
| 39 | + cout << "\nArea of Triangle => " << 0.5 * d1 * d2; |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +// // define class Rectangle by inheriting class Shape |
| 44 | +class Rectangle : public Shape |
| 45 | +{ |
| 46 | +public: |
| 47 | + // instance member function to display the area |
| 48 | + void displayArea() const override |
| 49 | + { |
| 50 | + cout << "\nArea of Rectangle => " << d1 * d2; |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | +// // define class Circle by inheriting class Shape |
| 55 | +class Circle : public Shape |
| 56 | +{ |
| 57 | +public: |
| 58 | + // instance member function to display the area |
| 59 | + void displayArea() const override |
| 60 | + { |
| 61 | + cout << "\nArea of Circle => " << 3.14159 * d1 * d1; |
| 62 | + } |
| 63 | +}; |
| 64 | + |
| 65 | +int main() |
| 66 | +{ |
| 67 | + // // create an instance of Triangle |
| 68 | + Triangle t1; |
| 69 | + t1.setData(4, 3); |
| 70 | + t1.displayArea(); |
| 71 | + |
| 72 | + // // create an instance of Rectangle |
| 73 | + Rectangle r1; |
| 74 | + r1.setData(4, 5); |
| 75 | + r1.displayArea(); |
| 76 | + |
| 77 | + // // create an instance of Circle |
| 78 | + Circle c1; |
| 79 | + c1.setData(7.5); |
| 80 | + c1.displayArea(); |
| 81 | + |
| 82 | + cout << endl; // Add new line |
| 83 | + getch(); |
| 84 | + return 0; |
| 85 | +} |
0 commit comments