int& fun(){
    int a = 10;
    cout << &a << endl;
    return a;
}
int main() {
    int& r = fun();
    cout << r << endl;
    cout << &r << endl;
    return 0;
}

outputs of the code above are:

0xbf8567b4
10
0xbf8567b4

and when i change int& r = fun(); to int r = fun();
the addresses differ, they become:

0xbfa831e4
10
0xbfa83210

why this happens?

and i have another question that why i still can get "10" printed, "r" is the reference of the local variable "a" in fun(), isn't it that the "a" variable gets destroyed and the reference "r" becomes referencing nothing when the function calling finishes?

any help will be greatly appreciated!

A reference in C++ is another name of an object. The fun() function returns a reference to the local int variable called a. After int& r = fun(); r is another name of INEXISTENT object: local (automatic) variable a (int object in automatic atorage - usually stack) of fun does not exist after fun() call ended.
That's why you get different results: you are trying to print a contents of reused stack space where variable a lived.
Of course, it's a logical error in your code. Good compilers (VC++, for example) print warning message in that case (VC++: "warning C4172: returning address of local variable or temporary").

I tested this in eclipse and it did warn me.
But I can't understand why the INEXISTENT object still holds the value 10, and can still be passed either to int& a or int a?

I did another test with a my own class:

class Apple{
    string name;
public:
    Apple(string);
    string getName();
};
string Apple::getName(){
    return this->name;
}
Apple* fun(){
    Apple apple("HELLO");
    return &apple;
}
int main() {
    Apple* apple = fun();
    cout << apple->getName() << endl;
    return 0;
}

and this time i got nothing printed, why?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.