Quote:Ok so I've played around with C/C++ for about 10 years or so,
How can you program for 10 years in a language, and not know the difference between passing by value and passing by reference? Just wondering, since it's a pretty crucial and fundamental concept for both, performance as well as code safety.
Quote:void foo(myClass argObject) { // code }
This creates a new object, and copies all the values in the object you passed into new instance. (sizeof(myClass) == ???). Changing argObject doesn't affect what was passed as parameter.
Quote:void foo(myClass * argObject) { // code }
Copies the value of pointer to myClass. (sizeof(myClass*) == 4 (32-bit))
Quote:void foo(myClass & argObject) { // code }
Copies the value of reference. Similar to pointer, with restrictions that apply to references. (sizeof(myClass&) == 4 (32-bit))
Later two examples modify the passed object directly - so whatever you pass as parameter, may get modified by the function. If first example, changes are discarded once function returns, unless myClass contains pointers or references to other objects.
Copying here refers to stack allocated objects, and the sizes as they are defined by your architecture. How the allocations will be performed exactly, and what is allocated will depend on calling convention. For passing by value, the object's members will always have the same layout though.
In reality, inlining will frequently be performed to reduce copying. Depending on the compiler, this may happen automatically, or when explicitly specified.
Const modifier may also affect what compilers considers to be safe to do, but cannot fully enforce it. Marking various parts of parameter as const will determine what you may or may not modify.
In that case, there might be no difference between how you pass the parameter.
For all the intricate details about various other issues and how things are done in practice,
this covers it pretty well, but it's scattered over multiple articles.
Then there's also:
void foo(myClass * &argObject)
(I hope I got this right).
This should pass reference to pointer, meaning function may change the value of the parameter that was passed. If you pass x into such function, and function changes argObject's value to another pointer, x will change too.