Is there a difference

Is there a difference declaring a function like this:

 
int exampleFunction() { return value;}


or like this:

 
const int exampleFunction() { return value;}


I mean i understand the difference if theres an ampersand sign:
 
const int& exampleFunction() { return value;}


But what is the difference between the 2 first ones?

int exampleFunction() { return value;} Returns a copy of value

const int exampleFunction() { return value;} Returns a const copy of value

const int& exampleFunction() { return value;} Returns a const reference to value

The difference between the first two: The first one returns a regular copy. Do whatever you want with it. The second returns a const copy, so you can't change value at all. In practice, I don't think I've ever seen the second example. Code will almost always return a copy, a reference, or a const reference.

EDIT: See this thread for thread for some discussion http://stackoverflow.com/q/8716330/2887128
Last edited on
I suppose a compiler might be able to make some optimizations with the second example? If not, I don't see how it could be useful.
The word "const" in "const int exampleFunction()" has no meaning. There is no difference between #1 and #2. Compilers will warn:

test.cc:6:1: warning: 'const' type qualifier on return type has no effect [-Wignored-qualifiers]
const int exampleFunction() { return value;}
^~~~~~
1 warning generated.


test.cc:6:27: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]


test.cc(6): warning #858: type qualifier on return type is meaningless
  const int exampleFunction() { return value;}
  ^


(note, if you return a class type (class/struct/union), then const is meaningful)
Topic archived. No new replies allowed.