How to access variables defined and declared in one function in another function?

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

Leave a Comment