mangi03@ca.com wrote:
[reformatted annoying line numbering & indentation][color=blue]
> class ref
> {
> public:
> void getNumber();
> ref getObj();
> void neg(ref& Obj);
> int i;
> };
>
> void ref::getNumber() {
> cout<<"Please enter a number "<<endl;
> cin>>this->i;
> cout<<"Assigned value is "<<this->i<<endl;
> }
>
> ref ref::getObj() {
> return (*this);
> }
>
> void ref::neg(ref& Obj) {
> Obj.i=-Obj.i;
> cout<<"In the neg func by reference "<<Obj.i<<endl;
> }[/color]
This is rather bad style: the function does not make any use of
the object. Consider either making it static, or having a free
function:
void neg(ref& Obj)
[color=blue]
> int main() {
> ref refObj;
>
> refObj.getNumber();
> refObj.neg(refObj.getObj());
>
> ref tmpObj=refObj.getObj();
> refObj.neg(tmpObj);
>
> cout<<"neg of the number in tmpObj is "<<tmpObj.i<<endl;
> cout<<"neg of the number in refObj is "<<refObj.i<<endl;
>
> return 0;
> }
>
> You can see that if I call the neg() function with another function
> call as as argument, copiler is giving mismatch, but If I split it up
> (line 50 and 51), it works fine.
> Please let me know any thoughts on this....easier way to get around
> this problem as I have 1000's of such function calls in a product
> which I am porting from windows to Linux. I wouldn't want to go to
> each and every place and split it up into two statements.[/color]
Your code is a great example of why you can't bind a temporary to a
non-const reference! You should have seen in the output that tmpObj.i
was negative, whereas refObj.i was positive. The code:
refObj.neg(refObj.getObj());
has no effect on refObj (a copy of refObj is passed to neg(), not
the actual refObj, and then the copy is destroyed as soon as it has
been negated). The reason that this rule was added to the language
was precisely to catch this sort of error. If you do want to forge
ahead with this useless code, then you have to explicitly name the
temporary object.