Function Return Types

If const plays an important role when passing parameters, what role, if any does const play with function return types?

Up till now we have only returned built-in types by value. As we saw in the class on strings, user-defined types can also be returned by value. So the questions are

  1. Can you return a built-in type or user-defined type by "const value" and if so, does it make sense?
    Yes; almost never

  2. Can you return a built-in type or user-defined type by reference and if so, does it make sense?
    Yes; sometimes but there are pitfalls. We do this often when we are returning a reference to a parameter that was passed in by reference. Checkout this code which illustrates one of the pitfalls and (hopefully) results in a compiler error or warning. int& AddOne ( int n ) { int x = n + 1; return x; }

  3. Can you return a built-in type or user-defined types by reference to const and if so, does it make sense?
    Yes; sometimes but the same pitfalls exists.
The answers to these last two questions will be more important after we study classes at which time we'll see more examples of them and their pitfalls.


Last Modified: Monday, 28-Aug-2006 10:15:58 EDT