If I create a class like so:
// B.h #ifndef _B_H_ #define _B_H_ class B { private: int x; int y; }; #endif // _B_H_
and use it like this:
// main.cpp #include <iostream> #include <vector> class B; // Forward declaration. class A { public: A() { std::cout << v.size() << std::endl; } private: std::vector<B> v; }; int main() { A a; }
The compiler fails when compiling main.cpp. Now the solution I know is to #include 'B.h', but I’m curious as to why it fails. Neither g++ or cl‘s error messages were very enlightening in this matter.
The compiler needs to know how big ‘B’ is before it can generate the appropriate layout information. If instead, you said
std::vector<B*>, then the compiler wouldn’t need to know how big B is because it knows how big a pointer is.