I just had an interview. I was asked what is a \"forward declaration\". I was then asked if they were dangers associated with forward declarations.
I could not answer to
I'd say any danger is eclipsed by the gains. There are some though, mostly related to refactoring.
namespace
to another, coupled with using
directives, can wreak havoc (mysterious errors, hard to spot and fix) - of course, the using
directives are bad to start off with, but no code is perfect, right?*Consider
template class Y;
int main()
{
Y<> * y;
}
//actual definition of the template
class Z
{
};
template //vers 1.1, changed the default from int to Z
class Y
{};
The class Z
was changed afterwards as the default template argument, but the original forward declaration is still with int
.
*I've recently ran into this:
Definition:
//3rd party code
namespace A
{
struct X {};
}
and forward declaration:
//my code
namespace A { struct X; }
//3rd party code
namespace B
{
struct X {};
}
namespace A
{
using ::B::X;
}
This obviously rendered my code invalid, but the error wasn't at the actual place and the fix was, to say the least, fishy.