-5

I have this class:

class A
{
private:
    int a;
public:
    int getA();
    void setA(int a=2) ;
};

and a function:

A& func()
{
A a;
a.setA(777);
return a;
}

and in main:

A a;
a=func();
cout<<a.getA();

and i get "777". but as i know it shouldnt get me any value since the local "a" in the function has been deleted. so why do i get the right value?

shl mig
  • 19
  • 1
  • What makes that value "right" exactly? Didn't you just say you know you shouldn't get that value? If you shouldn't get it, how can it be right? – David Schwartz Dec 05 '17 at 10:40
  • Possible duplicate of [C++ Returning reference to local variable](https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable) – tofro Dec 05 '17 at 10:41
  • 1
    Possible duplicate of [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – moooeeeep Dec 05 '17 at 10:42
  • I stole a cookie in the shop and still I am not in jail. Does this prove that stealing cookies is legal? Obviously no – 463035818_is_not_an_ai Dec 05 '17 at 10:45
  • @tobi303 You say obviously - but looking at prison numbers I'm pretty sure it's not obvious to all ;) – UKMonkey Dec 05 '17 at 10:53
  • 2
    I REALLY don't get it why this question deserves 7 (seven) downvotes. It has a minimal, complete (well, complete unless you aren't too stupid to type in 2 trivial getters and a main function) example, it shows a clear problem and a clear question. – user2328447 Dec 05 '17 at 11:23
  • @user2328447 I'd guess people feel the question's existence stems from solid lack of research and find it's not useful to have yet another question of this kind around. But sometimes people just seem to overreact (in one direction or the other). – moooeeeep Dec 05 '17 at 12:25

2 Answers2

1

Because the behaviour of your code is undefined, and appearing to work correctly on at least one occasion is an acceptable manifestation of undefined behaviour.

You may well get "777": a NUL-terminated const char[4] type.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Like Bathsheba already answered, returning a reference to a temporary variable causes undefined behaviour.

Unfortunately, in my experience two bad things come together regarding this:

  • Due to the structure of a compiler, the reference will very often be 'seemingly' correct, like in your example.
  • The "return reference to temporary" issues only a compiler warning, not an error!

Both things together makes this problem very dangerous, because it can be easily missed and work even for years... until the day of that very important presentation.

Solution is to treat this warning as an error (consult your compiler's documentation for compiler flags) or - even better - treat all warnings as errors.

user2328447
  • 1,807
  • 1
  • 21
  • 27