Nigel Horne
Nigel Horne

Reputation: 53

syntax error when using ifstream

It's been a long time since I've done any C++. What's wrong with this code?

#include <iostream>
#include <fstream>

using namespace std;
main()
{
    ifstream& ifs("foo.txt");
}

Gives:

$ g++ foo.cc 
foo.cc: In function ‘int main()’:
foo.cc:7:25: error: invalid initialization of non-const reference of type ‘std::ifstream& {aka std::basic_ifstream<char>&}’ from an rvalue of type ‘const char*’
  ifstream& ifs("foo.txt");

Upvotes: 0

Views: 478

Answers (3)

timmerov
timmerov

Reputation: 179

semantically, a reference is a pointer. so your code doesn't compile for the same reason this code doesn't:

main()
{
  ifstream* ifs("foo.txt");
}

as others have said, you want to create an object of type ifstream. not a reference (nor a pointer) to it.

Upvotes: 0

Sessamekesh
Sessamekesh

Reputation: 430

Passing values by reference isn't done in the variable declaration, but instead in the parameter list of the function using the ifstream object. For example, your function main might look like this:

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    ifstream ifs("foo.txt");
    myFunction(ifs);
}

and your called function should look like this:

void myFunction(std::ifstream& in_stream)
{
    // ...
}

If you need the C++11 reference type (which I doubt, but maybe), try this:

ifstream ifs("foo.txt.");
std::ref<std::ifstream> ifs_ref(ifs);

That works in a lot of cases where doing a regular by-ref wouldn't.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385375

You used a & when you should not have done.

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    ifstream ifs("foo.txt");
}

Upvotes: 3

Related Questions