hi all,
while i am learning the overloading operators ,i studied the following syntax

ostream&operator<<(ostream &, classname&);

i understand how it works but only something that i don't understand is the use of (&) with ofstream class ?at this point what's happening ?
also i notice that i can do it also to functions like

foo&(){
//code here
return //something
}

so what's meant by that ?

thanks

First, you are confused... :-)

The ostream& operator<<(ostream& output, classname& cn) returns a reference to the output object, allowing multiple outputs to the same stream in one expression such as cout << "foo" << "bar" << " " << dec << 1001 << endl;, which would display "foobar 1001". Your example of foo&() {...} is invalid on the face of it. Your compiler should give you an error about that.

thank you , i got what you said about ofstream&...
second ,it doesn't give an error i use the last version of microsoft compiler
ex:

int&foo(){
    int i = 1;
    return i;
}

//main
cout<< foo() << endl;

i feel it doesn't make sense as i reference a varible that will be destroyed after return ,so why i need to reference it.

You are right ... it is NOT correct code to return a ref to that temporary value.

You need to have your compiler warnings turned ON. (You seemed to have all turned off.)

I see you changed your question; first, you asked about this:

foo&(){...

and then you changed that to this:

int& foo(){...

Presumably, the first one was a typo.

In C++, the second is invalid (and the first, but I'm callign that a typo). You can, however, return a const reference to a variable that is local to that function (i.e. created inside that function on the stack, such that ordinarily it would no longer exist when the function finishes). Basically, so long as you return a const reference, its lifetime gets extended so you can keep using it.

This is discussed by Herb Sutter (he's a face in the C++ world; if you stick with C++, you'll come across his name every so often) in his excellent GotW column; http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

Herb Sutter states on that page:

Visual C++ does allow Example 2 but emits a "nonstandard extension used" warning by default.

so presumably your Microsoft compiler is letting you get away with what is invalid C++ code. Is it giving a warning?

This is something else you'll come across more of; various compilers let you do things they really shouldn't. There is often an option in the compiler to increase warning and error levels to disallow these non-standard exceptions, and I recommend you do so; particularly as a beginner, sticking inside the C++ standard is a good idea.

Edited 2 Years Ago by Moschops

This article has been dead for over six months. Start a new discussion instead.