[Solved] String return from member function in C++


In C and C++ as opposed to C# and Java, variables do not need to be allocated in dynamic memory, which includes strings and character arrays.

If you need or want to return pointers from a function, they must point to some variable that won’t disappear after execution leaves the function. The two popular techniques are to use static variables or variables allocated from dynamic memory. Both static and dynamically allocated variables will be around after the execution leaves the function.

You may be confusing std::string with C style character arrays. The std::string class is an object and can be return from a function like an integer or double.

Technically, a C-Style string can be returned from a function without using pointers. Much like returning an array of integers.

Common practice in C is to return pointers to an array to refrain from copying large data structures. So the convention is to return a pointer to C-Style string and the target must be either static or dynamically allocated, so the target of the pointer doesn’t disappear after execution leaves the function.

solved String return from member function in C++