Review of Creating a Class in C++


In previous computer science classes, you have learned that the typical design of C++ programs is to have two files when you create a class:

Once you have the class defined, then you need a main function to test the code. Good programming practice involves putting the main function in a separate file. This makes a total of three files.

If you have been working in Java or any other programming languages, you may be foggy on the C++ syntax. The following is an example of a Circle class with a main.cpp file used to test this code.

circle.h

#include <iostream>
using namespace std;
#define PI 3.14159

class Circle
{
   public:
      //Constructors
      Circle();
      Circle(double radius);

      //Functions
      double getRadius();
      istream &readRadius(istream& is);
      void setRadius(double radius);
      double getArea();
      double getCircumference();

   private:
      double radius;
};

circle.cpp

#include "circle.h"

//Constructors. If no radius is specified, the default is 5.
Circle::Circle()
{
   radius = 5.0;
}
Circle::Circle(double radius)
{
   //because the data member is also called radius, you need to use "this->"
   this->radius=radius;
}


//Functions
double Circle::getRadius()
{
   return radius;
}

//Read the radius from some input stream (for instance cin or an ifstream object)
istream& Circle::readRadius(istream& is)
{
   is >> radius;
   return is;
}

void Circle::setRadius(double radius)
{
   this->radius=radius;
}

double Circle::getArea()
{
   return (PI*radius*radius);
}

double Circle::getCircumference()
{
   return (2*radius*PI);
}

main.cpp

#include "circle.h"
#include <iostream>
using namespace std;

int main()
{
   Circle c1;
   Circle c2(20.2);
   Circle c3;

   cout << "Please Enter the radius for c3:  ";
c3.readRadius(cin);
cout << endl << "Details of c1:" << endl; cout << "Radius is: " << c1.getRadius() << endl; cout << "Area is: " << c1.getArea() << endl; cout << "Circumference is: " << c1.getCircumference() << endl; cout << endl << "Details of c2:" << endl; cout << "Radius is: " << c2.getRadius() << endl; cout << "Area is: " << c2.getArea() << endl; cout << "Circumference is: " << c2.getCircumference() << endl; cout << endl << "Details of c3:" << endl;
cout << "Radius is: " << c3.getRadius() << endl;
cout << "Area is: " << c3.getArea() << endl;
cout << "Circumference is: " << c3.getCircumference() << endl; return 0; }

To compile and run this code, you can use the following commands on the command-line:

Notes: