Creating a class. Header file?

I have created a class "Clock". I'm following from an example out of my book, and everything compiles fine except for one thing, the header file at the top. I'm confused on what a header file is. I wrote "Clock.h" because that's what the books example is. The error I'm getting says "Clock.h file not found". Do I need to save just the clock class in a different file, and have my main method in a totally different file too? Thanks.

All the code below is in the same file.


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
#include "Clock.h"
#include <iostream>
using namespace std; 

int main(int argc, const char * argv[])
{
    Clock c1;
    c1.set();
    c1.print();
    c1.tick();
    c1.tick();
    c1.print();
    Clock c2;
    c2.set(999);
    for (int i = 0; i < 100000; i++)
        c2.tick();
    c2.print();    
    
    
    return 0;
} // End main method

class Clock
{
public:
    void set (unsigned long t = 0)
    {
        ticks = t;
    }
    void tick()
    {
        ticks++;
    }
    void print()
    {
        cout << "Current ticks == " << ticks << endl;
    }
    
private:
    unsigned long ticks;

};  // End class Clock 

The class Clock definition is meant to be in another file called "Class.h".

Edit: So yes, you are correct. The main() and class Clock are meant to be in separate files.
Last edited on
Just like how functions need to be declared before their use, so do classes. Clock.h would include the class declaration. It probably looks like this:

1
2
3
4
5
6
7
8
9
class Clock
{
public:
    void set (unsigned long t = 0);
    void tick();
    void print();
private:
    unsigned long ticks;
};


However if you add that you'd get an error as the set (unsigned long t=0) cannot be done twice. The class below looks like it was written for a header so it's better in this case to just cut and paste that into your header.
As well as Stewbond's code in the Clock.h file, you would have the definitions of the functions in a Clock.cpp file.

You can get your IDE to do this for you with the class wizard.

The Clock.cpp file might look like this:

1
2
3
4
5
6
7
8
9
void Clock::set (unsigned long t = 0) {
        ticks = t;
}
void Clock::tick() {
        ticks++;
}
void Clock::print() {
        cout << "Current ticks == " << ticks << endl;
}


So you will have 3 files altogether.

Hope all goes well.
Last edited on
Topic archived. No new replies allowed.