The thing is that you pass the int by value in both cases. Then it doesn't matter if you return this local copy of num by value or by reference (your compiler should complain about this version) ...
Here is what you probably want:
1 2 3 4
int& readRef(int& num) {
// do something
return num;
}
@mtrenkmann : thanks. it's a typing mistake. I actually meant it the way you said. But, even then it's not performing as i thought. Can you help me out?
You cant send a reference to a local variable(member)
Thats right, but in his/her case the variable is not local because its passed by reference. Then you can return by reference, its just kind of forwarding, no problem.
readRef( &t) = 18;
You should never write code like this. What is the intent? Does readRef change the value of its argument? And if so, this value would be immediately overridden! So why not simply writing i = 18;? Has readRef any side effects? Very confusing!
Furthermore your code is incorrect: return *(i+0); adds zero to an address, which makes no sense.
@sathya691 Can you post an example of your intended usage? You definitely should go with references instead of pointers. There are reasons why C++ has them.
You should never write code like this. What is the intent? Does readRef change the value of its argument? And if so, this value would be immediately overridden! So why not simply writing i = 18;? Has readRef any sideeffects? Very confusing!
sathya691 needs to change the value of the argument, not inside the function, but somewhere else by sending the reference.
If sathya691's intend was to change the value of the argument, inside the readRef, he could do what you've just said
And if so, this value would be immediately overridden! So why not simply writing i = 18;
so what is the intend of readRef( &t) = 18; the same as if you send a reference by overloading the () or [] operator in array classes.
Furthermore your code is incorrect: return *(i+0); adds zero to an address, which makes no sense.
it is not incorrect, it is the same as return *i; or the same as return i[0]; it is the way i am using for examples instead of a = ar[9 ]; i use a = *( ar + 9 ) ;
Well, ok the code is not incorrect in terms of invalid C++ code, but it is just not readable and this is no matter of taste. High-level languages such as C++ are for readability first, for humans, otherwise we could all write assembly.
Then I don't understand why you came up with things like arrays and operator overloading. The original post has nothing to do with it. Lets focus on the problem he/she has. Thanks.