Can anyone tell me how to access variables declared and defined in a function in another function. E.g
void function1()
{
string abc;
}
void function2()
{
I want to access abc here.
}
How to do that? I know using parameters we can do that but is there any other way ?
The C++ way is to pass abc
by reference to your function:
void function1()
{
std::string abc;
function2(abc);
}
void function2(std::string &passed)
{
passed = "new string";
}
You may also pass your string as a pointer and dereference it in function2. This is more the C-style way of doing things and is not as safe (e.g. a NULL pointer could be passed in, and without good error checking it will cause undefined behavior or crashes.
void function1()
{
std::string abc;
function2(&abc);
}
void function2(std::string *passed)
{
*passed = "new string";
}
Make it global then both can manipulate it.
string abc;
void function1(){
abc = "blah";
}
void function2(){
abc = "hello";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With