C++: A Rectangle class

Complete the class Rectangle: write its member functions area() and perimeter(). main reads the width and height and prints both.

What to build

The member functions area() and perimeter() of a Rectangle class.

Requirements

  • Use the object's own width and height inside each function.
  • Return the results, and let main print them.
  • Keep main as it is.

Input

Two whole numbers: the width and the height (1 to 10000).

Output

area A perimeter P

Constraints

The width and height are from 1 to 10000.

Example

Input:

3 4

Output:

area 12 perimeter 14

Why it works

Inside a member function, width and height mean the members of the object the function was called on, so the same code works for every rectangle.

Examples

Example 1 · Input
3 4
Expected output
area 12 perimeter 14
Example 2 · Input
1 1
Expected output
area 1 perimeter 4

Hints

Hint 1

area() returns width * height; perimeter() returns 2 * (width + height).

Hint 2

Inside a member function, width and height mean the object's own members.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;

class Rectangle {
public:
    int width;
    int height;
    int area() {
        return width * height;
    }
    int perimeter() {
        return 2 * (width + height);
    }
};

int main() {
    Rectangle r;
    cin >> r.width >> r.height;
    cout << "area " << r.area() << " perimeter " << r.perimeter() << endl;
    return 0;
}

Lesson: Classes and objects →