title: How to have a file stream as a class member
body: <p>I have the following parser class that works in Visual C++</p>
  
  <pre><code>class Parser
  {
     private:
     const char* filename;
     std::ifstream filestream;
     std::vector&lt;std::string&gt; tokens;
     unsigned int linect;
  
     public:
     Parser(const char* filename);
     bool readline();
     std::string getstrtoken(unsigned int i) const { return tokens[i]; }
     int getinttoken(unsigned int i) const { return atoi(tokens[i].c_str()); }
  };
  
  Parser::Parser(const char* filename) :
     filename(filename),
     linect(0)
  {
     filestream = ifstream(filename); // OK in VC++, not with GCC?
  }
  
  bool Parser::readline()
  {
     std::string line;
     getline(filestream, line);
     std::stringstream ss(line);
     std::string token;
  
     tokens.clear();
     while(getline(ss, token, ' ')){ if(token != "") tokens.push_back(token); }
     linect++;
     return (filestream != NULL);
  }
  </code></pre>
  
  <p>But when I try to compile it with GCC 4.8.2, I get errors saying that I cannot assign to <code>filestream</code>. From what I read elsewhere on this site, you can do</p>
  
  <pre><code>std::ifstream filestream(filename);
  </code></pre>
  
  <p>but you cannot do</p>
  
  <pre><code>std::ifstream filestream;
  filestream = ifstream(filename);
  </code></pre>
  
  <p>which is essentially what I need to do if I want to declare <code>filestream</code> as a member of the <code>Parser</code> class and initialize it in the constructor.</p>
  
  <p>I would like to have the file stream kept within the <code>Parser</code> class so that those who use the parser don't need to declare and keep track of it. It seems to me that this should be self-contained in the <code>Parser</code> class since its internal methods (e.g. <code>readline()</code>) are the only ones that use it.</p>
  
  <p>Is there a way to achieve this that works with both platforms?</p>
  
  <p>Thanks.</p>
  
  <p><strong>edit:</strong> My fix was to explicitly call the <code>open()</code> method of <code>ifstream</code>. My parser class constructor now looks like:</p>
  
  <pre><code>Parser::Parser(const char* filename) :
     filename(filename),
     linect(0)
  {
     filestream.open(filename);
     // Do some checking to make sure the file exists, etc.
  }
  </code></pre>