Problem updating variables in class object

This is for a beginning programming course.

The program is supposed to create a class to store information about different archery shots, then compare two shots to find the one with the closest distance to the bulls eye.

I've implemented the class and everything compiles, however my x and y values will not update when the user enters data.

Any pointers toward my mistake will be much appreciated!

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
#include<iostream>
#include<string>
#include<cmath>
using namespace std;

class Archer
{public:

Archer();

void read();

bool better(Archer a) const;

void print() const;

private:
string name;
double xVal
double yVal;
double distance;
};

Archer::Archer()
{name = "none";
xVal=0;
yVal=0;
cout <<"x"<<xVal;
cout <<"y"<<yVal;
distance = sqrt(xVal * xVal + yVal * yVal);
}

void Archer::read()
{       cout << "Please enter the contestant's name:  ";
        cin >> name;
        cout << "Please enter their X Coordinate:  ";
        cin >> xVal;
        cout << "Please enter their Y Coordinate:  ";
        cin >>yVal;
}

bool Archer::better (Archer a) const
{return (distance < a.distance);
}

void Archer::print() const
{cout  << "The winner is " << name << " with a distance of " << distance << " from the center!\n";
}

int main() {
string again;
Archer first;
first.read();

bool more = true;
while (more){
Archer next;
        next.read();
        if(first.better(next)){
                first=next;}
        cout << "Is there another contestant (y/n)? ";
        cin >> again;
        if (again != "y"){
                more = false;}
}
first.print();
}
Actually the x and y values are updating, but distance is not.
Also default constructor will always create x = 0, y = 0, distance = 0 which is ok but printing them doesn't make sense
I printed them as a way to check if they were updating at the end of the user input. They are both printing out as 0, regardless of input. After I figure out what I've messed up, the print lines will be deleted.

Why would the distance not be updating? Am I not allowed to run an equation like that during the constructor?
Line 30: You're computing the sqrt of (0*0 + 0*0). You might as well just assign 0 to distance.

Lines 37,39: You're accepting new values of xVal and yVal. Where does distance get updated after inputing the new values? Hint: Copy line 30 and place it after line 39.

Am I not allowed to run an equation like that during the constructor?

You're not calling the constructor when you input new values. You're in read().

Thanks a ton for the insight right there! The whole problem makes quite a bit more sense now.
Topic archived. No new replies allowed.