user3239138
user3239138

Reputation: 143

passing a file to constructor to read

class Read
{
public:
    Read(ifstream &file)
    {
        mFile=file;
    }
private:
    ifstream mFile;
    string str;
};


int main()
{
    Read r("sample.txt");

    return 0;
}

I'm trying to use the constructor to read a file. I saw another example on stack overflow and tried to replicate it but failed. How do i properly read a file using a constructor. Is the syntax way off?

Upvotes: 1

Views: 6547

Answers (3)

juanchopanza
juanchopanza

Reputation: 227548

You can't copy or assign ifstreams, but you can initialize them from a string literal. So you could do this:

class Read
{
public:
    Read(const char* filename) : mFile(filename) {}
private:
    ifstream mFile;
    string str;
};

Note that this would make Read non-copyable and non-assignable. But move construction and move assignment would work.

Note that, if you really want to pass an ifstream, then the best you can do is pass a temporary, and use the data member's move constructor. You can achieve it with this constructor:

Read(ifstream&& file) : mFile(std::move(file)) {}

Usage:

Read r1("file.txt");                // const char* ctor
Read r2(std::ifstream("file2.txt"); // ifstream&& ctor

Upvotes: 2

David G
David G

Reputation: 96845

Standard file streams cannot be copied. The assignment in the constructor is invoking the stream's private (delete'd in C++11) copy-assignment operator. The correct way do this would be to invoke the appropriate constructor with the member initializer-list. The parameter should be of type std::string as well.

Read(const std::string& file)
   : mFile(file)
// ^^^^^^^^^^^^^
{ }

Upvotes: 0

Eejin
Eejin

Reputation: 839

"Sample.txt" isn't an ifstream. Instead, open the file with the passed string.

mFile.open(file); Where file is a c string.

Upvotes: 1

Related Questions