How on earth are these undefined

I literally initialized them in main, and they dont get called until they are initialized so I don't know why I am getting an error, also fyi my program is not done yet, I still need to write my reset function, and actually call the startTimer() funciton

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
#include <iostream>
#include <Windows.h>

using namespace std;

class Timer {
private:
    int numSec;
    bool direction;

public:

    Timer(int x, bool y)
    {
        numSec = x;
        direction = y;
    }
    void reset() {

    }

    void startTimer() {
        if (direction = false) {
            for (int i = 1; i < lengthUp; i++) {
                cout << i << endl;
                Sleep(1000);
            }
        }
        else {
            for (int i = lengthDown; i > 0; i--) {
                cout << i << endl;
                Sleep(1000);
            }

        }
    }
};


int main()
{
    int lengthUp, lengthDown;
    cout << "How long do you want the timer to count up for";
    cin >> lengthUp;
    cout << "How long do you want the timer to count down for";
    cin >> lengthDown;

    Timer countUp(lengthUp, false);
    Timer countDown(lengthDown, true);



}
Inside of startTimer(), did you perhaps intend to use numSec instead of lengthUp?
Last edited on
Also note that the following does not do what you want:

 
if (direction = false) {

It sets direction to false and because it's always false it will always jump to the else part of the if statement.

You probably meant:

 
if (direction == false) {

Which is normally written simply as:

 
if (!direction) {

! is the logical NOT operator.
Last edited on
Line 24,30: lengthUp and lengthDown are undefined. The compiler has not seen them yet when the class is compiled.

You need to change line 24 to:
 
        for (int i = 1; i < numSec; i++) {


And change line 30 to:
 
        for (int i = numSec; i > 0; i--) {



To expand on what others have said: lengthUp and lengthDown are defined as local variables in your main function. That means their scope is limited to just that function. They don't exist in any other context, so they don't exist within the Timer::startTimer() method.

In your main function, you pass the values of those variables to the constructor for Timer. However, that doesn't magically create variables with those names inside your Timer class. Timer stores the first value it's given in the variable numSec, so that's the variable you should use inside methods of the class.

Hopefully, that makes things clearer.
Last edited on
Topic archived. No new replies allowed.