how to access a local variable in another function?

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.

Answer

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
  }
}