Help Understanding Headers

Hello!

I have some programming experience in other languages so I understand how importing classes works. The #include statement takes care of that in C++. However, one thing I'm not quite grasping is headers. It's my understanding that headers work similarly to Java Interfaces? If this is the case, headers reference a class' functions but don't define them. If I'm still on track, then how would you declare more complex functions within a header?

For example if a function took a command line argument as a parameter, or took multiple parameters of multiple types, how would this appear in a header file? Which variables need declared in a header file, just the global ones?

Sorry for such an open ended question, I've been trying to find a good explanation of headers, and a thorough example of their usage for days now, to no avail.

Happy Weekend!

Oh! and I did read through this:
http://www.cplusplus.com/forum/articles/10627/2/
Last edited on
your header files are used to define your classes or functions, while .cpp files are your implementation files. So jumping from your example, you have a class foo:

foo.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef foo_h_      //make sure the header file is only included once
#define foo_h_

class foo {
    public:
        foo();
        void doSomething(int x, int y, char t);
    private:
        int bar;

};

#endif 


foo.cpp
1
2
3
4
5
6
7
8
9
#include "foo.h"
foo::foo(){

}

void foo::doSomething(int x, int y, char t)
{
    //....
}
Thank you! I don't know why that helped more than the guide, but it did. :)

Not to ask a separate question, but what about functions that are part of an external file but not part of a class? How would I run those?

For instance:

foo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "foo.h"
foo::foo(){

}

void foo::doSomething(int x, int y, char t)
{
    //....
}

//end of foo class

bool randomcheckmark()
{
   //....
}


I don't suppose this is anything like Python where I can just type filename.functionname(etc)?
In your code you have "end of foo class", but your question before that talks about functions that are not part of a class, so sorry if I'm confused, but:
When you "include" something, you can think of it as literally replacing that line with what you have in the other file. The "foo::" syntax only applies to a member function of the class "foo".

Also, in case it isn't clear, it isn't like Java "interface", that's something else.

Edit: Oh, I think I misunderstood. You *can* define a function like that, but that probably isn't the way you'd want to organize code. You wouldn't want to define or implement a function in a header or .cpp file that corresponds to a particular class that has nothing to do with that class.
Last edited on
I think I get it now. Thanks people!
Topic archived. No new replies allowed.