Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stream

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);
    }
like image 378
schindi Avatar asked May 02 '26 17:05

schindi


1 Answers

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);
like image 72
sehe Avatar answered May 04 '26 07:05

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!