schindi
schindi

Reputation: 55

C++ How to initialize a std::istream* although constructor is protected

I want to use a class with stream-members.

My code looks like that:

//! pushes a Source and InputFilters into a filtering_istream
class FilterChain {
public:
    //! create an empty FilterChain
    FilterChain(){
        init();
    }

private:
    //! the stream to connect Source and InputFilters together
    io::filtering_istream* m_filteringStream;
    //! stream to use by other classes
    std::istream* m_stream;

    void init(){
        std::streambuf* streamBuffer = m_filteringStream->rdbuf();
        m_stream->rdbuf(streamBuffer);
    }
};

I get an error message that the std::basic_istream constructor is protected:

/usr/include/c++/4.8.1/istream: In member function `void FilterChain::init()': /usr/include/c++/4.8.1/istream:606:7: Error: `std::basic_istream<_CharT, _Traits>::basic_istream() [with _CharT = char; _Traits = std::char_traits]' is protected

I tried stream references as well but that caused the same error. Any ideas how to fix this?

EDIT 1:

Thx to sehe I fixed it with a new init() like that:

void init(){
        std::streambuf* streamBuffer = m_filteringStream->rdbuf();
        m_stream = new std::istream(streamBuffer);
    }

Upvotes: 3

Views: 11272

Answers (1)

sehe
sehe

Reputation: 393084

Your code shown doesn't actually contain the problem at all.

The problem is you are trying to default-construct an istream object somewhere (not in your question code).

You need at least a buffer to initialize it with:

std::filebuf  m_dummy;
std::istream  m_stream(&dummy);

Now, you can reassign the rdbuf like you did. See also, e.g. How can I switch between fstream files without closing them (Simultaneous output files) - C++

Update As Dietmar just confirmed, you could just pass a nullptr for the streambuf* argument:

std::istream  m_stream(nullptr);

Upvotes: 6

Related Questions