# C++ program to find the area of hexagon using class

Learn, how can we find the area of hexagon using the class and object approach?
Submitted by Shubh Pachori, on September 04, 2022

## Problem statement

Given the length of sides, find the area of hexagon using the class and object approach.

Example:

Input:
Enter Length of sides: 12.5

Output:
Area of Hexagon is 405.949

## C++ code to find the area of hexagon using the class and object approach

#include <math.h>
#include <iostream>
using namespace std;

// create a class
class Hexagon {
// private data members
private:
float length, area;

// public member functions
public:
// putSides() function to insert
// length of sides
void putSides() {
cout << "Enter Length of sides: ";
cin >> length;
}

// getArea() function to calculate
// the area of the hexagon
double getArea() {
// calculating area of the hexagon
area = (6 * (length * length)) / (4.0 * tan((M_PI / 6)));

// returning area
return area;
}
};

int main() {
// create object
Hexagon H;

// float type variable to store area
float area;

// calling putSides() function to
// insert length of the side
H.putSides();

// calling getArea() function to calculate
// area of the Hexagon
area = H.getArea();

cout << "Area of Hexagon is " << area << endl;

return 0;
}

### Output

Enter Length of sides: 23
Area of Hexagon is 1374.38

### Explanation

In the above code, we have created a class Hexagon, two float type data members length and area to store the length of sides and area of hexagon, and public member functions putSides() and getArea() to store the length of sides and to calculate the area of the hexagon.

In the main() function, we are creating an object H of class Hexagon, reading the inputted values by the user using putSides() function, and finally calling the getArea() member function to calculate the area of the hexagon. The getArea() function contains the logic to calculate the area of the hexagon and printing the result.