I hope my question is not too stupid, but I could not find any help googling it, nor reading the website.
1. In c++ the prototype of a function returning a pointer is somehing like
*pVariable function(argType arg,...)
But i keep reading codes which contains
&pVariable funcion(argType arg,...)
What does is mean ?
2. I also don't understand this prototype syntax:
Variable &function(...)
Is it the same than previously mentionned ?
3. Same thing for some variable declarations, what is exactly this syntax?
int& i;
is is the same like int* i ?
I got that in the case of pointers, with addresses and values.
But here that's not used to declare a reference to a function or a variable, or ? Those prototypes are the declarations of the functions themselves. And To declare a reference to a variable I do something like int *i=0;
Then what is:
int& i;
ClassA& = ClassA(...);
??
Yes, it does. However, that's an invalid function definition. What you're doing there is mixing an object declaration within a function definition. Remove var from it, then it becomes a valid function definition. Also, make sure you don't return a reference to a local object. Bad things happen.
Okay, thank you for the answers. So those 3 are exactly the same :
int& function(int a,int b)
int &function(int a,int b)
int* function(int a,int b)
and those 4 too :
int *i;
int* i;
int &i;
int& i;
That's it ?
I'm a bit confused wih that. For an example here is a sample of code I read:
1 2 3 4 5 6
template<typename T>
const T &limit(const T &val, const T &minimum, const T &maximum)
{
if(val < minimum) return minimum;
return val > maximum ? maximum : val;
}
The function is returning some variable of T type and not *T, right ?
int& function(int a,int b)
int &function(int a,int b)
int* function(int a,int b)
The 1st & 2nd are the same, but the 3rd is different. Pointers are not the same as references.
Esteban wrote:
1 2 3 4
int *i;
int* i;
int &i;
int& i;
Again, the 1st & 2nd are the same, and the 3rd & 4th are the same. However, the 1st & 2nd are not the same as the 3rd & 4th.
Edit:
It doesn't matter where the asterisk (*) or ampersand (&) appears between the type and identifier, so long as it's there. For example, these are valid (but annoying) declarations:
I'm a bit confused wih that. For an example here is a sample of code I read:
1 2 3 4 5 6
template<typename T>
const T &limit(const T &val, const T &minimum, const T &maximum)
{
if(val < minimum) return minimum;
return val > maximum ? maximum : val;
}
The function is returning some variable of T type and not *T, right ?
That function will return a reference to constant data, and not a pointer.