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)?
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)
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).
Code:
class SomeBigObjClass;
...
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).
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.
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.
Bookmarks