1

I just go through an interview where i was asked how can i access local variable of function to other function. code flow-

class A{
    public:
    void fun1(int a){
       int local_var=a;
    }
    
    void fun2(){
        // here i want to use local_var of fun1
        //you are not allowed to do any changes either in fun1 and class
        // however you can do anythingh in fun2.
    }
  
}

is there any way to do it.

2
  • 2
    If local_var goes out of scope the moment fun1 returns and you're not allowed to modify the function, clearly, you can't read the value in any other scope. Commented Apr 1, 2021 at 5:52
  • Now if you're willing to trigger UB, it's possible that adding a similar int stack variable to fun2 without ever initializing it, and calling fun2 immediately after fun1, may end up getting you the original value of local_var as the "trash" value. Commented Apr 1, 2021 at 5:54

1 Answer 1

5

Local variables do not exist if the function is not currently executing and even then, they only "exist" in a very narrow scope.

Here local_var is a short-lived int that only springs into being during fun1 executing. The instant that function is done, it's gone.

fun2() has no access to it because it doesn't exist at that point. Even if you call fun2() within fun1() it still doesn't have access because fun2() has its own local scope that's different.

If you want something shared you need either a property on your class if this should be shared within a single member of this class, or a static variable if it's shared between all members.

What you probably mean is this:

class A{
public:
  int m_a = 0;

  void fun1(int a) {
     m_a = a;
  }
    
  void fun2() {
     // Can use m_a here
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.