You can return a refernce to anything that is not local to your function. You could return a reference to a member variable :
class Foo{ HugeObject bar;public: const HugeObject& Bar() const { return bar; } Foo& Bar( const HugeObject& val ) { bar = val; return *this; } friend std::ostream& operator<<( std::ostream&, const Foo& ); friend std::istream& operator>>( std::istream&, Foo& );};
Note that returning a non-const reference to a member variable is a violation of encapsulation, as the receiver of the value could use it to modify the variable as if it were public - if that''s what you want, get over it and just make it public instead of fooling yourself.
You can also return a reference to a parameter, not necessarily *this, for example to enable call chaining.
With iostreams, you need to return the stream object by reference to allow calls like
std::cout << FooObj1 << FooObj2 << FooObj3 << std::endl;
std::ostream& operator<<( std::ostream& os, const Foo& obj ){ os << obj.bar; return os;}std::istream& operator<<( std::ostream& is, Foo& obj ){ is >> obj.bar; return is;}
iostreams operator overloads are typically friend non-members of the class you are adding stream support for.
[
Start Here ! |
How To Ask Smart Questions |
Recommended C++ Books |
C++ FAQ Lite |
Function Ptrs |
CppTips Archive ]
[
Header Files |
File Format Docs |
LNK2001 |
C++ STL Doc |
STLPort |
Free C++ IDE |
Boost C++ Lib |
MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan