PDA

Click to See Complete Forum and Search --> : overloading ostream for a class


NOMADMAN
May 7th, 2002, 12:13 PM
I have many values stored in a class under the protected: heading. In the public section of the function I have a ostream friend ( ostream & operator << (ostream &o, const class c) ). In the ostream friend I tried o << on the values stored in the class ( o << c.value; ). I get the compiler error 'value' : cannot access protected member declarded in class.

First off why doesn't this work, shouldn't the program make a copy of the class in the varible c, I thought when you passed a class by value it called the default constructor and copy constructor to make a copy of your class. Why can't the function who owns the class varible not access the protected memebers?
I'm not going to have to make a public function to return all the values from the protected section, am I? That would seriously suck!
I know there must be an easier way, some one care to enlighten the dim-witted

NOMAD

CornedBee
May 10th, 2002, 05:08 AM
Only functions of the class itself and derived classes can access protected members. There is no "owner of variable" concept in C++.
First, you should make the prototype of the overload
ostream & operator << (ostream &os, const myclass &c);

because you don't want a copy to be made - it takes too long and does no good.

To grant this function access to private and protected class members, you must add this line to the class declaration:
friend ostream & operator << (ostream &, const myclass &);