Tillman
Tillman

Reputation: 5

std::ostream object in class is "not accessible through a pointer or object"

I use several functions in a class that pass an ostream via their function interfaces, allowing error messages to be output. How can I bind all ostream objects to a single instance, which I could then redirect to a file if necessary?

The relevant parts of my code look something like this:

#include <iostream>

class Example
{
    public:
    Example(){} //<--Error: "std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 390 of "/usr/include/c++/9/ostream") is inaccessible C/C++(330)

    void DoSomething()
    {
        FunctionWithOstream(out);
    }

    private:
    std::ostream out; //in my case, the ostream is currently not needed for the time being.

    void FunctionWithOstream(std::ostream& out)
    {
        out << "Something";
    }
};

At the first curly bracket of the constructor (or all constructors in the program) I get the following error message:

protected function "std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 390 of "/usr/include/c++/9/ostream") is not accessible through a "std::basic_ostream<char, std::char_traits<char>>" pointer or object

Or for the short example code I pasted here:

"std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 390 of "/usr/include/c++/9/ostream") is inaccessible

Upvotes: 0

Views: 437

Answers (2)

Jarod42
Jarod42

Reputation: 218248

std::ostream is not default constructible, you probably want reference/pointer instead:

class Example
{
public:
    Example(std::ostream& out = std::cout) : out(out) {}

    void DoSomething() { FunctionWithOstream(out); }

private:
    std::ostream& out;

    void FunctionWithOstream(std::ostream& os) { os << "Something"; }
};

Upvotes: 4

Tillman
Tillman

Reputation: 5

Ok, I have found a solution:

#include <iostream>
#include <sstream>

class Example
{
    public:
    Example(){} //<--Error: "std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 390 of "/usr/include/c++/9/ostream") is inaccessible C/C++(330)

    void DoSomething()
    {
        FunctionWithOstream(outStream);
    }

    private:
    std::ostringstream outStream; //std::ostringstream instead of std::ostream is working fine.

    void FunctionWithOstream(std::ostream& out)
    {
        out << "Something";
    }
};

instead of std::ostream std::ostringstream can be used to receive the functions streams.

Upvotes: -1

Related Questions