In C++ and Objective-C, I've gotten into the habit of forward-declaring any necessary classes that do not need to be defined in the header, and then importing the header files defining those classes in source files if needed.
Is there ever a situation in which this wouldn't be a good idea?
(I know the big disadvantage of forward declaration is the limited usability of an incomplete type. For the purpose of this question, assume that in the header I only need to use the forward-declared class as an incomplete type.)
A forward declaration is not so much dangerous in itself, but it is a code smell. If you need a forward declaration, it means two classes are tightly coupled, which usually is bad. Thus it is an indication that your code may need refactoring.
One big benefit is faster compilation times, as a forward declaration takes less time for the compiler to parse than a complete class definition. This can make a very significant difference for large projects with many include files.
The Google style guide recommends against using forward declarations, and for good reasons: If someone forward declares something from namespace std, then your code exhibits undefined behavior (but will likely work).
As the name itself implies, forward declaration is just a Declaration and not a definition. So, you will declare saying the compiler that it is a class and I just declaring it here and will provide you the definition when am gonna use it. So, normally you forward declare in the Header file and #include in the .
Sometimes you can change the semantics of the program subtly without raising any errors
class Foo;
template < typename T>
struct Trait
{
static const int MY_TYPE = -1;
};
// Lets say this is Foo.h
//class Foo
//{
//};
//template<>
//struct Trait<Foo>
//{
// static const int MY_TYPE = 1;
//};
void TestFunction(Foo& f)
{
std::cout << Trait<Foo>::MY_TYPE << std::endl;
}
Consider the above code and the commented out code lives in a header. If the header is included TestFunction will print 1 otherwise -1
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