I had a few questions in a technical interview that I thought I knew, but wanted to double-check (they said I passed it, but I was unsure about these):
-
A variable declared inside a Class Method… Can that be used outside of that method, like for instance in another method? (I said no)
-
Can a variable declared inside a method be passed as a parameter to another method?
(I said yes but I wasn’t sure)
This is for an entry-level C++ position and I’m used to C, so I wanted to double-check my understanding of C++/OO concepts.
A variable within a class method, that’s instantiated within that method and wholly contained within that method, can only be used within that method. Its lifetime is finite. Edit: to clarify, I’m not saying it can’t be passed to another function call within the function scope and I’m not talking about instantiating a member variable or static variable.
Yes, you can pass it to another method if that method is called from within the method it exists. Why? Because its lifetime it tied to the parent method, not the one that is called from within the method.
Let me illustrate: