Area of Rectangle using Constructor in C++


This is a program to calculate the area of a rectangle using classes and objects in C++.

  • The Area class has two private variables length and breadth, and three public member functions GetLength(), Calculation(), and Display().
  • The constructor of the class initializes the length to 7 and breadth to 4. The GetLength() function prompts the user to enter the length and breadth of the rectangle. The Calculation() function calculates the area of the rectangle, which is the product of length and breadth. The Display() function takes the area as an argument and displays it on the screen.
  • In the main function, two objects A1 and A2 of the class Area are created. The GetLength() function is called for object A1 to get the length and breadth of the rectangle from the user. Then the Calculation() function is called to calculate the area, which is stored in the temp variable. Finally, the Display() function is called with temp as an argument to display the area.
  • Then, the Calculation() and Display() functions are called for the A2 object, which uses the default values of length and breadth (7 and 4, respectively) set by the constructor to calculate and display the area.

Overall, this program demonstrates how classes and objects can be used to encapsulate data and behavior related to a rectangle's area.

Source Code

#include<iostream>
using namespace std;
class Area
{
  private:
    int length;
    int breadth;
  public:
    Area(): length(7), breadth(4){ }
    void GetLength()
    {
      cout<<"\nEnter length of the Rectangle: ";
      cin>>length;
      cout<<"\nEnter breadth of the Rectangle: ";
      cin>>breadth;
    }
    int Calculation()
    {
      return (length*breadth);
    }
    void Display(int temp)
    {
      cout<<"Area: "<<temp;
    }
};
int main()
{
  Area A1,A2;
  int temp;
  A1.GetLength();
  temp=A1.Calculation();
  A1.Display(temp);
  cout<<endl<<"\nDefault Area when value is not taken from user"<<endl;
  temp=A2.Calculation();
  A2.Display(temp);
  return 0;
}
To download raw file Click Here

Output

Enter length of the Rectangle: 20
Enter breadth of the Rectangle: 10
Area: 200
Default Area when value is not taken from user
Area: 28

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples