# Simple ifstream question

## Recommended Posts

__fold    202
I have this very simple problem and it drives me insane. I think I've missed something in c++... I have this:
#ifndef SCRIPT_H
#define SCRIPT_H

#include <fstream>

class Script
{
private:
std::ifstream in_;

protected:
std::string cachedMessage_;
unsigned int currentLine_;

public:
Script(void);
virtual ~Script(void);

unsigned int getCurrentLine() { return currentLine_; }

bool open(std::string inFile);
std::string nextMessage();
};

#endif


and in c++
bool Script::open(std::string inFile)
{
in_.open(inFile.c_str()); //Crash!
return in_.is_open();
}


Now, the program crashes when in_.open() is called. It gives me an access violation. Why? If I make in_ local then it doesn't crash.

##### Share on other sites
Pete_    198
You're not accidentaly doing something like this:

Script* s = 0;
.....
s->open("script.file");

Are you? It's happened to me before, quite annoying. Try breaking in Script::open and check that the this pointer is not null and is valid.

- Pete

##### Share on other sites
__fold    202
Pete_, yep, thanks, that's the problem...
I got tricked by the compiler since I had an other version of the open function that I could step through without any errors. But that one didn't access any members.

I almost did the same mistake just the other day but I found the problem right away then. Guess I'm tired...

thanks.

##### Share on other sites
Washu    7829
Just as a note, __fold, you should be passing a const reference to that string, and not a string object. Passing the string object results in unnesessary copying.

##### Share on other sites
__fold    202
Washu: Yes, I know, I changed some stuff when it didn't work...