Shashank Jain
Shashank Jain

Reputation: 479

Returing reference of Local variable from function is not giving an error

#include<iostream>
#include<conio.h>

using namespace std;

 /* test class: created the reference of 
    abc class locally in function getRef() 
    and returned the reference.*/

class abc {
    int var;

    public:
        abc():var(5) {}
        abc(int v):var(v) {}
        abc & getRef() {
            abc myref(9);
            return myref;
        }
        void disp() {
            cout<<var<<endl;
        }       
};

int main() {
    abc a;
    abc b=a.getRef(); 
    b.disp();  /* this statement executed perfectly. 
               I think compiler should throw error here. */
    getch();
    return 0;
}

Compiler should throw compilation error. Please explain ?

Upvotes: 0

Views: 288

Answers (2)

johnsyweb
johnsyweb

Reputation: 141790

G++ will warn you about this appropriately, but it shouldn't error and certainly not at b.disp();, since you're not actually using the return value on that line and you copied it on the line above.

: In member function ‘abc& abc::getRef()’:
:17: warning: reference to local variable ‘myref’ returned

If your compiler doesn't warn you about this, then check your warning level.

Also:

#include<conio.h>

This does not make for portable code.

Upvotes: 0

user743382
user743382

Reputation:

The compiler shouldn't flag b.disp(); as an error, as that isn't where the error is. The error is at return myref;, and the reason this isn't a hard error is that it is very tough in general to determine whether an object's lifetime will have ended after the return. In this case, it's easy, and some compilers do try to warn about it. Check your warning level.

Edit: with gcc, by the way, the warning is enabled by default and looks like "warning: reference to local variable '...' returned".

Upvotes: 1

Related Questions