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
Show 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