Hi All,

I have doubt in my mind regarding declaration of cin and cout object . As per my understanding cin and cout both object are accessible in main then they shouldn't have protected.in below code snippet i have overloaded both input and output operator and
while giving new name (ofstream obj) to user defined version of this operator , I am getting error like obj is protected and can't be accessed here. Anybody can suggest .

#include<iostream>
using namespace std;

class overload
{

public:
int var_a;
overload (int fun_a=10): var_a(fun_a)  {}
friend ostream operator >> (ostream &output, overload &);
friend istream operator << (istream &input, overload &);
};

overload operator +( int a , overload &p1   )
{ overload k;
    return ( k.var_a= a+k.var_a);


}

ostream &operator <<( ostream &output, overload &s1)
{

    output<<"value of object output:"<<s1.var_a<<endl;
    return output;

}
istream &operator >>( istream &input, overload &s1)
{

    input >> s1.var_a;
    return input;
}



int main()
{
overload s1,s2;
//ostream obj;
//obj<<"enter the value of object"
cout<<"enter the value of object";
    cin>>s2;
    cout<<s2;




    return 1;


}

Seeing the actual error would help, but I suspect it's coming from line 40. The ostream class doesn't expose a public default constructor. Really your only option is to pass in a pointer to a streambuf object that handles all of the nitty gritty details of reading from the stream.

Note that streambuf also has a protected constructor, which means you need to derive your own custom stream buffer class to pass into ostream. Alternatively you can reuse an existing streambuf. For example, if you want your ostream to essentually do the same thing as cout, you can do this:

#include <iostream>
#include <ostream>

using namespace std;

int main()
{
    ostream obj(cout.rdbuf());

    obj << "Hello, world!\n";
}

It's largely pointless though, since cout is already available.

Hi,

Thanks for your replay , But still onedoubt in my mind that how cin and cout are make available in main function .

iostream declares them to be publicly visible (within the std namespace). If you open up iostream you'll see how they're declared, but all you may see are extern declarations.

In c++11 compiler, i am getting below error :

c:\mingw\include\c++\4.9.0\ostream:384:7: error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits<char>]' is protected
       basic_ostream()

if i haven't mistaken then constructor of ostream class seems to be protected and below code snippet also indicates that still by using reference it can be made possible because it ignores straight away construction .

ostream& obj= std::cout;

obj<<"Hello World";
This question has already been answered. Start a new discussion instead.