Circle::Circle(double radius)
{
pi = 3.14159; // <-- add this line, can u see why?
setRadius(radius);
}
There is no need to make pi a class property, especially given the potential for errors like yours. pi is just a constant and is not unique to the class. Make it a (global) constant.
#include <iostream>
usingnamespace std;
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle
{
private:
// To hold a value for pi
double pi;
// To hold the radius
double radius;
public:
// The default constructor sets
// radius to 0.0 and pi to 3.14159.
Circle();
Circle(double radius);
// The overloaded constructor accepts
// the radius as an arguemnt.
// Mutator function for the radius
void setRadius(double rad);
// Accessor function for the radius
double getRadius();
// The getArea function returns the
// circle's area.
double getArea();
// The getDiameter function returns the
// circle's diameter.
double getDiameter();
// The getCircumference function returns
// the circle's circumference.
double getCircumference();
};
#endif
Circle::Circle()
{
radius = 0.0;
pi = 3.14159;
}
Circle::Circle(double radius)
{
pi = 3.14159;
setRadius(radius);
}
void Circle::setRadius(double rad)
{
radius = rad;
}
double Circle::getRadius()
{
return radius;
}
double Circle::getArea()
{
double area = pi * (radius*radius);
return area;
}
double Circle::getDiameter()
{
return radius + radius;
}
double Circle::getCircumference()
{
return 2 * pi * radius;
}
// Demo program
int main()
{
// To hold a radius
double radius;
cout << "Enter a radius" << endl;
// Get the radius.
cin >> radius;
// Create a Circle object with the
// specified radius.
Circle circularObject(radius);
// Display the circle's data.
cout << "Radius: " << circularObject.getRadius() <<endl;
cout << "Area : " << circularObject.getArea() << endl;
cout << "Diameter: " << circularObject.getDiameter() <<endl;
cout << "Circumference: " << circularObject.getCircumference() << endl;
return 0;
}
Enter a radius
2
Radius: 2
Area : 12.5664
Diameter: 4
Circumference: 12.5664
Program ended with exit code: 0