
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to create one rectangle class and calculate its area
Suppose we have taken length and breadth of two rectangles, and we want to calculate their area using class. So we can make a class called Rectangle with two attributes l and b for length and breadth respectively. And define another function called area() to calculate area of that rectangle.
So, if the input is like (10,9), (8,6), then the output will be 90 and 48 as the length and breadth of first rectangle is 10 and 9, so area is 10 * 9 = 90, and for the second one, the length and breadth is 8 and 6, so area is 8 * 6 = 48.
To solve this, we will follow these steps −
Define rectangle class with two attributes l and b
define input() function to take input for l and b
define area() function to return l * b, which is the area of that rectangle
Example
Let us see the following implementation to get better understanding −
#include <iostream> using namespace std; class Rectangle{ private: int l, b; public: void input(int len, int bre){ l = len; b = bre; } int area(){ return l * b; } }; int main(){ Rectangle r1, r2; r1.input(10, 9); r2.input(8, 6); cout << "Area of r1: " << r1.area() << endl; cout << "Area of r2: " << r2.area() << endl; }
Input
(10, 9), (8, 6)
Output
Area of r1: 90 Area of r2: 48
- Related Articles
- JavaScript program to find Area and Perimeter of Rectangle
- Golang Program to Create a Class and Compute the Area and Perimeter of a Circle
- Program to calculate area and perimeter of Trapezium
- Calculate the area and perimeter of the following shapes:Q.1 Calculate the area of Square and rectangleQ.2 Calculate perimeter of Square and rectangle."\n
- C Program for Area And Perimeter Of Rectangle
- Python Program to Create a Class and Compute the Area and the Perimeter of the Circle
- Program to calculate area of Enneagon
- Program to calculate Area Of Octagon
- Program to calculate area and perimeter of equilateral triangle
- Program to calculate area and volume of a Tetrahedron
- Java program to find the area of a rectangle
- Swift Program to find the area of the rectangle
- Golang program to find the area of a rectangle
- Haskell Program to Find the Area of a Rectangle
- Swift Program to calculate the volume and area of Sphere
