Suppose I have a class called Class
:
Class.h
:
#pragma once
class Class
{
public:
std::vector<int> x();
};
Class.cpp
:
#include <vector>
#include "Class.h"
std::vector<int> Class::x()
{
return std::vector<int>();
}
I suppose that this code should not compile since std::vector
isn't defined in Class.h
. But the code works. It doesn't work if I include the needed headers (in this case it's just vector
) after including Class.h
. But as long as the needed headers are imported before the inclusion of Class.h
, everythig works fine. Also it doesn't work if I try to include Class.h
somewhere alone and try to use it. So for example this code won't work:
#include <iostream>
#include "Class.h"
int main()
{
Class c;
auto x = c.x();
x.push_back(1);
x.push_back(2);
x.push_back(3);
for (auto i : x)
std::cout << i << ' ';
}
But if I include the needed headers, It works fine. So in this example, it works if I include the vector
header (also has to be before the inclusion of Class.h
):
#include <vector>
#include "Class.h"
#include <iostream>
int main()
{
Class c;
auto x = c.x();
x.push_back(1);
x.push_back(2);
x.push_back(3);
for (auto i : x)
std::cout << i << ' ';
}
I'm thinking of #include
as just copy-pasting. In Class.h
, no header is being included. How is it possible to say that this function will return an std::vector
without it being defined? And why including the headers in the source file makes it as if it was included in the header file?
You do not compile Class.h
, you compile the cpp file which #include
s Class.h
.
If you include the vector header before Class.h
in main.cpp
, then, after the preprocessor step, your main.cpp
file will have the contents of vector
header, followed by the contents of Class.h
, followed by other code in main.cpp
. So the definition of vector
will be visible in Class
.
If you compile just the Class.h
header separately, you will get an error. I advise you always do this to check if your header files have all the necessary headers and can compile without relying on side effects.