
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Create Rectangle Class and Calculate 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