0

I wrote a testing class in a header like this:

File.h

#ifndef FILE_H
#define FILE_H

class File {
    fstream stream;
public:
    File(string path);
    ~File();
};

File::File(string path) {
    stream.open(path);
}

File::~File() {
    stream.close();
}

#endif // FILE_H

And in another file I included and used it like this:

t.cpp

#include <iostream>
#include <string>
#include <fstream>
#include "/home/unlimiter/Documents/programming/modules/cpp/uio/File.h"
using namespace std;

int main(int argc, char *argv[]) {
    File f("/home/unlimiter/tst");
}

Why does errors occur (like that fstream is not defined) when I do that?

I tested writing the class inside 't.cpp' and that works fine

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

4
  1. There is indeed no such thing as fstream. It is spelt std::fstream.
  2. Same for std::string.
  3. Some people will tell you to work around this by writing using namespace std. Don't (if only because you'd need to do it in a header, which is considered ungood).
  4. It would be better to put those #includes in the file that needs them, i.e. the header itself. Otherwise you're relying on including a bunch of things together for any of it to work (which is also considered ungood).
  5. Try not to use absolute paths in #include directives: it makes your source code difficult to move around your computer, or to other computers. This kind of thing is better managed by your compilation environment / bulid system.
  6. Now you need to move your function definitions into the .cpp file (or perhaps a new File.cpp!) because as soon as you include your header in more than one translation unit, the linker will complain about multiple definitions.
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055