Rectangle Class in C++ to Calculate Area and Perimeter

In this exercise, you will implement a C++ class called "Rectangle" with methods to calculate both the area and the perimeter of a rectangle. The class will have attributes such as length and width, and it will contain member functions to compute the area and perimeter based on these values. This task will help you practice working with classes, constructors, and member functions in C++. It also provides a practical example of implementing basic geometric calculations using object-oriented programming.

Group

Object-Oriented Programming in C++

Objective

1. Define a class called "Rectangle" with attributes for length and width (double).
2. Add a constructor that initializes the rectangle with the given length and width.
3. Implement two member functions: one to calculate the area and another to calculate the perimeter.
4. In the main function, create an object of the Rectangle class with given dimensions and display the area and perimeter.

Implement a Rectangle class with methods to calculate area and perimeter.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include the standard input/output library
using namespace std;

// Define the 'Rectangle' class
class Rectangle {
private:
    double length;  // Private attribute for length
    double width;   // Private attribute for width

public:
    // Constructor to initialize the 'Rectangle' object with length and width
    Rectangle(double l, double w) {
        length = l;  // Set the length to the passed value
        width = w;   // Set the width to the passed value
    }

    // Member function to calculate the area of the rectangle
    double calculateArea() {
        return length * width;  // Use the formula length * width to calculate the area
    }

    // Member function to calculate the perimeter of the rectangle
    double calculatePerimeter() {
        return 2 * (length + width);  // Use the formula 2 * (length + width) to calculate the perimeter
    }
};

int main() {
    // Create an object of the 'Rectangle' class with length 5 and width 3
    Rectangle rect1(5, 3);

    // Output the area and perimeter of the rectangle
    cout << "Area of the rectangle: " << rect1.calculateArea() << endl;  // Print area
    cout << "Perimeter of the rectangle: " << rect1.calculatePerimeter() << endl;  // Print perimeter

    return 0;  // Return 0 to indicate successful execution
}

 Output

Area of the rectangle: 15
Perimeter of the rectangle: 16

Share this C++ Exercise


More C++ Programming Exercises of Object-Oriented Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.