DEFAULT

Attempting to return a reference to local variable vs instance

attempting to return a reference to local variable vs instance

An instance variable is a variable that's bound to the object itself. Instance variables are declared in a class, but outside a method. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class. Instance variables are available to any method bound to. There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this. Local variables do not get a default value. The compiler complains if you try to use a local variable before before the variable is initialised. However, instance variables always get a default value. If you don't explicitly assign a value to an instance variable, the instance variable .

2 thoughts on “Attempting to return a reference to local variable vs instance

Leave a Reply

Your email address will not be published. Required fields are marked *