C++ Programming/Programming Languages/C++/Code/Keywords/return

The   statement causes execution to jump from the current function to whatever function called the current function. An optional a result (return variable) can be returned. A function may have more than one   statement (but returning the same type).


 * Syntax:

Within the body of the function, the   statement should NOT   a pointer or a reference that has the address in memory of a local variable that was declared within the function, because as soon as the function exits, all local variables are destroyed and your pointer or reference will be pointing to some place in memory which you no longer own, so you cannot guarantee its contents. If the object to which a pointer refers is destroyed, the pointer is said to be a dangling pointer until it is given a new value; any use of the value of such a pointer is invalid. Having a dangling pointer like that is dangerous; pointers or references to local variables must not be allowed to escape the function in which those local (aka automatic) variables live.

However, within the body of your function, if your pointer or reference has the address in memory of a data type, struct, or class that you dynamically allocated the memory for, using the new operator, then returning said pointer or reference would be reasonable:

In most cases, a better approach in that case would be to   an object such as a smart pointer which could manage the memory; explicit memory management using widely distributed calls to  and   (or   and  ) is tedious, verbose and error prone. At the very least, functions which   dynamically allocated resources should be carefully documented. See this book's section on memory management for more details.

In this case the SOMETYPE object pointed to by the returned pointer may not be modified, and if SOMETYPE is a class then only const member functions may be called on the SOMETYPE object.

If such a const   value is a pointer or a reference to a class then we cannot call non-const methods on that pointer or reference since that would break our agreement not to change it.