forgive my ignoricy, but if I understand correctly there are 3 ways for passing function parameters
1. call by value - which make a temp object -> do not change my value
2. using pointers
3. using reference
2 & 3 do change the value, but what is the difference between them?
is one of them more efficent than the other?
is any of them do a copy operation for the entire struct being send as parameter (like in call by value)?
thank you very much
November 6th, 2003, 12:24 PM
The main difference is that when calling by pointer, the value can be 0. With reference, it needs to be something valid.
There's no difference in performance between the two.
If you don't want to allow the function to change the value, make sure you make the parameter const.
November 6th, 2003, 03:42 PM
I know that while using call by value the entire object (instead of a pointer) is sent/copied to the function
and I know that is not the situation while using pointers as function parameters, but what happend when you send the object by reference does the entire object is sent?
I mean when my func looks like that MyFunc(MyObject& obj)
what is sent the entire object (which is a heavy operation) or a pointer? (like hen using pointers)
November 6th, 2003, 03:44 PM
It's like a pointer. Nothing is copied.
November 6th, 2003, 03:50 PM
Pass by reference doesn't copy the object at all. There should be no difference in passing an object by reference, or passing in a pointer to an object.
If you have a large object, that you are passing into functions, you're probably better off declaring the functions to accept a const reference (as mentioned before).
int MyFunc (const SomeBigObjClass &a)
// I cannot modify a in here, only read from it
Unless, of course, your function can take no object at all (i.e. a NULL pointer).
November 7th, 2003, 02:15 AM
so what is the difference betwenn using opinters & using reference as functions parameter?
why do both way exist
and which way is better when I need to pass my function an object that I would like to change
I mean from 2 aspects 1. efficency 2. readabilty
November 7th, 2003, 03:09 AM
If you are just passing an object, using a reference is better in terms of readability. As from the perspective of efficiency, both are the same.
However, if you need to pass a pointer to an array of object, there is no choice but to use a pointer. This is because the address stored by the reference cannot be modified once after initialization.
November 7th, 2003, 10:16 AM
References behave better sytactically when you are using objects with operator overloads.
In method2, you need to dereference first before using the overloaded operators. Pointers are not objects and don't behave like them. They are necessary largely because of the C heritage, and they also do have their uses as stated in other responses. I would say that references are more of the correct OO approach.