I have a question about when to use forward declaration vs. include header. I know that there are a lot of questions similar to this out there, but there's just one thing that's a bit confusing.
I've seen the following way in a source code I was looking at:
classA.h
#ifndef H_CLASSA
#define H_CLASSA
class classB;
class classA {
public:
classA(B* b);
};
and then in classA.cpp:
#include "classA.h"
#include "classB.h" // dependency
classA::classA(B* b) { b->someMethod(); }
In cases like this I've just put #include "class.b" in the classA-header from the start since A has a dependency on class B and uses it. But I don't get why you would forward declare classB first in the header and then include the classB.h in the source file?
Thanks in advance!
ClassA, it's about the users ofClassA. If you#include "classB.h"intoclassA.hthen it'll be#included transitively into all files that useClassAbut may or may not useClassB. Since you are usingClassBinclassA.cpp, you'll have no choice but need to include it there but you can save your users the burden of the#includeby keeping the#includelocal to the implementation file and using a forward declaration inclassA.h. - 5gon12eder