HackerRank ‘C++ Rectangle Area’ Solution

Short Problem Definition:

Create two classes:

Rectangle
The Rectangle class should have two data fields-width and height of int types. The class should have display() method, to print the width and height of the rectangle separated by space.

RectangleArea
The RectangleArea class is derived from Rectangle class, i.e., it is the sub-class of Rectangle class. The class should have read_input() method, to read the values of width and height of the rectangle. The RectangleArea class should also overload the display() method to print the area width*height of the rectangle.

Link

Rectangle Area

Complexity:

Does not apply.

Execution:

Solution:
// because cstdio is superior!
#include <cstdio>
/*
 * Create classes Rectangle and RectangleArea
 */

class Rectangle {
    public:
        int width = 0;
        int height = 0;

        virtual void display() {
            printf("%d %d\n", width, height);
        }
};

class RectangleArea: public Rectangle {
    public:
        void read_input() {
            scanf("%d %d", &amp;width, &amp;height);
        }

        void display() override {
            printf("%d\n", width*height);
        }
};


If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

Facebooktwitterredditpinterestlinkedin