Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ forward declaration problem

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.

like image 251
Thomas Avatar asked Jun 03 '10 04:06

Thomas


People also ask

Why are forward declarations bad?

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.

Does C support forward declaration?

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.

How do you fix a forward declaration in C++?

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 };

Is forward declaration good practice?

- 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.


1 Answers

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

like image 102
chickeninabiscuit Avatar answered Sep 29 '22 23:09

chickeninabiscuit