You are correct about why func1 is invalid. The rest is also invalid because temporary objects can't bind to non-const references. If you change all references to const, func2-func6 will be valid (but maybe not what you want).
"The rest is also invalid because temporary objects can't bind to non-const references. If you change all references to const, func2-func6 will be valid."
I don't quite understand what you mean by temporary object, could you explain a bit or direct me to a reference or a page on some book?
I don't understand why we cannot initialize any variables in a function prototype, could you also explain a bit or show me a reference that explains it? I flip through C++ primer, but it does not say anything about such restriction...
When you have an integer literal, like 2, that will create a temporary object. The temporary object will only exist on that line. After the line has ended the temporary object will no longer exist. Keeping a reference to the temporary object would allow you to access a non-existing object in the lines below. You don't want that. That is why this is not allowed:
int& r = 2;
cout << r; // Not good. The object that r is referring to no longer exists.
const references are a bit different. You can use a const reference to extend the life time of the temporary object to have the same life time as the reference. Note that since it is a const reference you can't modify the object.
1 2 3 4
constint& r = 2;
cout << r; //
} // r goes out of scope so the temporary object that r is referring to is destroyed here.
I just tried, and it did not compiled at all. And all of them have such error: default argument for ‘int& <anonymous>’ has type ‘int’ . What does it have to do with inability to reference a temporary value?
As I said, you need const. void func2(int = 1, constint& = 2);
There is probably not much point passing an int by const reference compared to passing a regular int. void func2(int = 1, int = 2);
If you want the function to take a non-const reference, because you might want to modify the int variable that is passed to the function, you should probably not use default arguments for this function. void func2(int, int&);