Problem with returning an ostream by Reference vs Value

Hello,
I have this function declaration
friend std::ostream & operator<<( std::ostream & os, const Time & object );
that helps me display objects using << operator the only thing I don't understand is that the complier is forcing me to return by reference vs by value when I pass by value I get a (cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>') error but I'm accessing the same information when I return by reference why am I receiving this error for returning by value.
I thought maybe because I'm copying the information before using it when I return by value but I'm still accessing the same information either way. It seems I'm not fully understanding some mechanics in returning by value vs refenence.
Here is the function definition:
1
2
3
4
5
std::ostream & operator<<( std::ostream & os, const Time & object )
{
	os << object.hours << ", " << object.minutes << "\n";
	return os;
}

Thanks for any help I receive.
closed account (3hM2Nwbp)
What's the private member you're trying to access? (It should be in the compiler output)

It sounds like a copy constructor from what you've written. I don't know offhand if std::ostream is copy constructable or not because there's nothing in the documentation regarding it.

Edit - Copying a stream would probably almost always be a bad idea anyhow.
Last edited on
Thanks std::ostream isn't copy constructable I knew creating a copy of the entire ostream class isn't the best practice I was just wondering why I wasn't allowed too.
probably because copy construction doesn't always make sense for the derived concrete classes

in other words, std::ostream is so abstract that copy construction of the derived concrete classes themselves may not be well defined

for example, it might be easy to copy construct an ostringstream in memory, and it actually might make sense, but I'm not sure what it would mean to copy a ofstream (have you just copied the file in memory or on disk? a partially outputted stream in memory? has it been flushed? if so, is the copy flushed? if they are pointing to the same file on disk, what does it mean to write to one, flush and then write to other and flush?) - it could be totally ambiguous
Information about an open file has never been copyable. That is because once you make a copy, then you can modify the file and update one set of data about the file, but all others instantly become out of date.

The C library did a smart thing by making you handle a pointer to it, so you can copy pointers that all act on the same data. Hence:

1
2
3
FILE* fp = fopen( ... );
fprintf( fp, "Hello %s!\n", users_name );
fclose( fp );

I'm not sure why the STL doesn't do the same sort of thing under the hood (with a little reference counting), but things are what they are.

Alas.
Topic archived. No new replies allowed.