Constructor

Pages: 12
What took you three days to respond?
closed account (48T7M4Gy)
1
2
3
4
5
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.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
using namespace 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
Last edited on
Topic archived. No new replies allowed.
Pages: 12