HackerRank 'C++ Rectangle Area' Solution

Martin Kysel · August 21, 2020

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.

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", &width, &height);
        }

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

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.