I'm a C++ noob. I have a foo.cpp file which defines a function,
void sort() {
// details of sort algorithm
}
I have not defined this in the corresponding header file, but I get no compilation error. I noticed this is taken as a static method. Is that the case? What exactly have I done here?
EDIT:
I've noticed that inside this method I can't use this, (ex: this->bar), hence my assumption that this is a static function. This actually happened when I wanted a 'private' method, but forgot to declare it in the header file. Is there an actual use of such a function?
The cpp files can be compiled ahead of time. This doesn't work in you #include them, as it needs to actual "include" the code into your program each time it compiles it. If you just include the header, it can just use the header file to determine how to use the precompiled cpp file.
You can write a C program or a C++ program without including any header files. Note: C and C++ are different languages and have different rules. Still, the following complete program happens to be valid C (as of C99) and valid C++, and includes no headers: int main() {}
A template is not like a function which can be compiled into byte code. It is just a pattern to generate such a function. If you put a template on its own into a *. cpp file, there is nothing to compile.
The answer to the above is yes. header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs. NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.
It is not invisible outside of that compilation unit, it is not bound to a single compilation unit, it is just a definition that needs a declaration in order to be called. Like any other definition.
wtf.cpp:
#include <iostream>
void f(){ std::cout<< "f();"; }
omg.cpp:
void f(); // I can declare wherever I use it.
int main(){ f(); }
$ g++ wtf.cpp omg.cpp && ./a.out
Output: f();
No, it is not taken as a static function. It is just not visible to the other transllation unnits, and so you cannot use it.
The difference in regard to a static method is, that the linker sees the function. So if you define a function with the same name in another translation unit, you will probably either get a linker error (best case) or the wrong method called at times.
PS: I talk about a functions rather than methods here, because in C++ a method typically is part of a class, and you cannot define a method for a class if that method isn't declared in that class' declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With