views:

242

answers:

6

Hi,

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.

+2  A: 

How did you forward declared it? The problem could be in that std::ifstream is a typedef and not a class.

Kirill V. Lyadvinsky
+4  A: 

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

Ash Kim
A: 

If you want to forward declare some iostreams classes, you can simply include <iosfwd>. That header provides forward declarations for these classes.

sth
+2  A: 

You actually have two problems.

The first is that forward declaring a typedef is rather difficult in C++, as Kirill has already pointed out.

Th second is that ifstream is a typedef for a specific template instantiation of basic_ifstream -- in order for the compiler to be able to expand the template, it must already have the body of the template defined, meaning you can't forward declare an instantiated template.

Blair Holloway
+1  A: 

You're missing the semicolon after your class definition of A.

rlbond
A: 

Do the following (if you already include std header file before your own, there's no need to forward declare anymore):

In your cpp file:

#include <iostream>
#include "a.h"    

In your a.h file:

using namespace std;
class A {
  ifstream *instream;

};
Khnle