user3150201
user3150201

Reputation: 1947

Why can't I initialize an ifstream in the initializer list of the constructor of a class?

#include <fstream>
#include <iostream>

using namespace std;

class file_reader {

public:
    file_reader(const char* file_name) : file(ifstream(file_name)) { }

    char operator[](int index) const {
        file.seekg(index);
        return file.get();
    }

private:
    ifstream file;

};

I get an error: 'std::ios_base::ios_base(const std::ios_base&)' is private. Seems like the code is trying to call a constructor higher in the hierarchy. Although ifstream has a constructor that takes a const char*. What's the problem?

Upvotes: 1

Views: 1525

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

By creating a temporary ifstream(file_name) then initialising file from it, you're trying to invoke file's copy constructor, and this fails because that constructor is private where it is declared (in the base ios_base); streams cannot be copied.

I'm sure you meant to write this:

file_reader(const char* file_name) : file(file_name) { }

Remember, this:

struct T
{
   S object;
   type() : object(arg) {};
};

in terms of initialising a S is much like:

int main()
{
   S object(arg);
}

Upvotes: 8

Related Questions