|
| 1 | +// // Create a base class called shape. Use this class to store two double type values that could be used to compute the area of figures. Derive two specific classes called Rectangle and parallelogram from the base shape.Add to the base class, a member function setData() to initialise base class data members and another member function displayArea() to compute and display the area of figures.Make displayArea() as a pure virtual function and redefine this function in the derived classes to suit their requirements.Using these three classes, design a program that will accept dimensions of a square or a parallelogram interactively, and display the area. |
| 2 | + |
| 3 | +// // Header files |
| 4 | +#include <iostream> |
| 5 | +#include <conio.h> |
| 6 | + |
| 7 | +// // use namespace |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +// // define ab abstract class Shape |
| 11 | +class Shape |
| 12 | +{ |
| 13 | +protected: |
| 14 | + // // instance member variables |
| 15 | + double length, breadth; |
| 16 | + |
| 17 | +public: |
| 18 | + // // constructor |
| 19 | + Shape(int l, int b) : length(l), breadth(b) {} |
| 20 | + |
| 21 | + // // pure virtual function to be overridden by derived classes |
| 22 | + virtual void displayArea() const = 0; |
| 23 | +}; |
| 24 | + |
| 25 | +// // define class Rectangle by inheriting an abstract class Shape |
| 26 | +class Rectangle : public Shape |
| 27 | +{ |
| 28 | +public: |
| 29 | + // // inheriting the constructor of the base class |
| 30 | + using Shape::Shape; |
| 31 | + |
| 32 | + // // override base class function displayArea |
| 33 | + void displayArea() const |
| 34 | + { |
| 35 | + cout << "\nArea of Rectangle => " << length * breadth; |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +// // define class Sphere by inheriting an abstract class Volume |
| 40 | +class Parallelogram : public Shape |
| 41 | +{ |
| 42 | +public: |
| 43 | + // // inheriting the constructor of the base class |
| 44 | + using Shape::Shape; |
| 45 | + |
| 46 | + // // override base class function displayArea |
| 47 | + void displayArea() const |
| 48 | + { |
| 49 | + cout << "\nArea of Parallelogram => " << 0.5 * length * breadth; |
| 50 | + } |
| 51 | +}; |
| 52 | + |
| 53 | +int main() |
| 54 | +{ |
| 55 | + double length, breadth; |
| 56 | + cout << "\nEnter Dimensions of A Rectangle => "; |
| 57 | + cin >> length >> breadth; |
| 58 | + |
| 59 | + // // create an instance of Rectangle |
| 60 | + Rectangle r1(length, breadth); |
| 61 | + r1.displayArea(); |
| 62 | + |
| 63 | + cout << "\n\nEnter Breadth And Height of A Parallelogram => "; |
| 64 | + cin >> breadth >> length; |
| 65 | + |
| 66 | + // // create an instance of Sphere |
| 67 | + Parallelogram p1(length, breadth); |
| 68 | + p1.displayArea(); |
| 69 | + |
| 70 | + cout << endl; // Add new line |
| 71 | + getch(); |
| 72 | + return 0; |
| 73 | +} |
0 commit comments