The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Pointers and References Returning Pointers And/Or References from Functions | ||
Returning Pointers And/Or References from Functions
When declaring a function, you must declare it in terms of the type that it will return, for example: int MyFunc(); // returns an intSOMETYPE MyFunc(); // returns a SOMETYPE int* MyFunc(); // returns a pointer to an int SOMETYPE *MyFunc(); // returns a pointer to a SOMETYPE SOMETYPE &MyFunc(); // returns a reference to a SOMETYPE
{ ... ... return p; } SOMETYPE &MyFunc(int &r) { ... ... return r; } Within the body of the function, the return statement should NOT return a pointer or a reference that has the address in memory of a local variable that was declared within the function, else, as soon as the function exits, all local variables ar destroyed and your pointer or reference will be pointing to some place in memory that you really do not care about. Having a dangling pointer like that is quite inefficient and dangerous outside of your function. 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. SOMETYPE *MyFunc() //returning a pointer that has a dynamically{ //allocated memory address is proper code int *p = new int[5]; ... ... return p; }
|
||
Home Pointers and References Returning Pointers And/Or References from Functions |