I have a header file that has some forward declarations but when I include the header file in the implementation file it gets included after the includes for the previous forward declarations and this results in an error like this.
error: using typedef-name ‘std::ifstream’ after ‘class’
/usr/include/c++/4.2.1/iosfwd:145: error: ‘std::ifstream’ has a previous declaration.
class ifstream;
class A
{
ifstream *inStream;
}
// End of A.h
#include <ifstream>
using std::ifstream;
#include "A.h"
// etc
Whats the norm for working around this?
Thanks in advance.
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.
In C/C++, Visual Assist can add a forward declaration for a referenced symbol, e.g. a pointer to a class, to make an unknown symbol known. The forward declaration, if sufficient, typically reduces compile time relative to a comparable include directive.
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };
- it's good practice to use forward declaration instead because you eliminate redundant dependencies by using it. Also note, that when you change the header file, it causes all files that include it to be recompiled.
Don't forward declare std:ifstream - just import <iosfwd>
instead.
ifstream is a typedef.
See here for further details: http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/group__s27__2__iosfwd.html
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