Shape Area (C++ Class Example)

By vaseline28 on Jan 27, 2009

Simply detects the Area of either a Rectangle or a Circle.

Snippet not made to be the most useful in the world, but to demonstrate a basic use of classes in C++.

I've been doing C++ for 2 days, so it's not the most amazing snippet in the world ;p

#include <iostream>
#include <string>
using namespace std;

class rectangleArea {
    float x, y;
public:
    void setRectangle_values (float, float);
    float rectangleAreaCalc () {return (x*y);}
};

class circleArea {
    float t;
public:
    void setCircle_values (float);
    float circleAreaCalc () {return (t*3.1415);}
};

void rectangleArea::setRectangle_values (float a, float b)
{
    x = a;
    y = b;
}

void circleArea::setCircle_values (float s)
{
    t = s*s;
}

int newlyOpened = 0;
int main ()
{
  if ( newlyOpened == 0)
  {
    cout << "Select either 'Rectangle' or 'Circle' to use.\n\n";
    newlyOpened = 1;
  }
  cout << "Which shape would you like to calculate the area of? ";
  string userShapeSelect;
  cin >> userShapeSelect;
  if ( userShapeSelect == "Rectangle" )
  {
      rectangleArea rectA;

      float UIrectangleLength, UIrectangleHeight;
      cout << "Enter [ Length ]: ";
      cin >> UIrectangleLength;
      cout << "Enter [ Height ]: ";
      cin >> UIrectangleHeight;

      rectA.setRectangle_values (UIrectangleLength, UIrectangleHeight);
      cout << "Total area of Rectangle [ length=" << UIrectangleLength << " ] and [ height=" << UIrectangleHeight << " ] is: " << rectA.rectangleAreaCalc() << "\n\n";

      main ();
  }
  else if ( userShapeSelect == "Circle" )
  {
      circleArea circA;

      int UIcircRadius;
      cout << "Enter Circle [ Radius ]: ";
      cin >> UIcircRadius;

      circA.setCircle_values (UIcircRadius);
      cout << "Total area of Circle [ Radius=" << UIcircRadius << " ] is: " << circA.circleAreaCalc() << " \n\n";

      main ();
  }
  else
  {
      cout << "Shape not recognised, please choose either [Rectangle] or [Circle]\n\n";
      main ();
  }
  cout << "There was an error running this program - please restart it\n\n";
  system("pause");
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.