Call a variable with local scope inside a method from main

Hello

I am quite new in C++ programming and have some trouble in understanding the scope of variables. I am reading a lot in my book about accesing and the scope operator :: but I can't figure it out:

I have a class with am method. I declared this method as static function in the header file and make the implementation in a corresponding cpp file that has the same name as the class. Now in the code of the function I am in a local scope because I am inside the {} parentheses and variables are valid and visible in this function block. Now I ask myself how to call a variable of this scope from another cpp file i.e. my main function. Especially I mean not the retun value of the function but rather any variable in this block.

Thanks for help and greetings

Last edited on
You can't. Local variables go out of scope at the end of the block where they are defined so even if you were able to access them from outside the function it wouldn't be safe to do so because the variables wouldn't exist at that point.
Last edited on
If you want to make a variable accessible outside of the function make this variable a member of the class [or global variable] or you can return a copy.
Thanks for answering.

So if it is not possible to access such a variable, is it possible to copy this local variable in such a way that main could access the copy of it?

Greetings

p.s.

coder777 and I post at the same time. Making the variable to a member is not possible because the value of the variable will calculated by runtime. I don't know it before.

By returning a copy, do you mean the general return statement of the function or something else?
Last edited on
Some possibilities:

- have the function return the value
- make the variable an output parameter (using pass-by-reference) rather than a local variable
- make the variable a data member of the object, rather than a local variable, and implement an accessor method on the class so that the calling code can obtain it.

Some others I wouldn't recommend, because they're problematic:

- make the variable a public data member of the class, rather than a local variable
- make the variable a global variable, rather than a local variable

Without seeing the code in question, it's hard to know what the most appropriate solution is, although it's probably not one of the last two.
Topic archived. No new replies allowed.