Reputation: 1319
In C++, what is the advantage of Implementation 1 over Implementation 2 indicated below. Since both are a kind of pass by reference, won't the memory be allocated from HEAP, in both the cases ? If that is the case, what is the advantage of one over the other.
Secondly, which methodology is better - Pass by value OR Pass by reference. When, one should use Pass by Value and when one should use Pass by reference.
Implementation 1:
main()
{
struct studentInfo { int Id; int Age; };
*studentInfo tom;
populateInfo (tom );
printf ("Tom's Id = %d, Age = %d\n", tom.Id, tom.Age);
}
void populateInfo ( struct studentInfo & student )
{
student.Id = 11120;
student.Age = 17;
return;
}
Implementation 2:
main()
{
struct studentInfo { int Id; int Age; };
*studentInfo *tom = new studentInfo;
populateInfo (tom );
printf ("Tom's Id = %d, Age = %d\n", tom->Id, tom->Age);
}
void populateInfo( struct studentInfo *student )
{
student->Id = 11120;
student->Age = 17;
return;
};
Upvotes: 1
Views: 280
Reputation: 37364
Memory allocation has nothing to do with type of formal parameters. Both functions,
void populateInfo ( struct studentInfo & student ); //1
void populateInfo ( struct studentInfo * student ); //2
can be called with object created in heap or in stack. The first implies that object already created, the second allows null argument.
Passing by reference is usually better because you avoid copying objects. However, for built-in types like char
, int
, etc it makes no difference from that point of view. Also, passing by reference lets you change value of argument.
Upvotes: 2
Reputation: 702
Your implementation with pointer will be more ressource efficient because the function only copies a reference (pointer) of the objet to work with.
The implementation with passing the object will create a copy of the object to use it in your function (so allocate more memory).
I suggest you to use const reference to your object in your function if you don't intend to modify it in your function:
Upvotes: 0
Reputation: 340218
There's probably one main difference between passing by address/pointer and passing by reference:
Which method might be an advantage depends on what you might need to do.
There are a couple other things that might be of consequence:
passing a pointer makes it more obvious at the call site that the object might be modified. I consider this a reason to favor the pass-by-address syntax, all other things being equal.
a reference cannot be 'reseated' to refer to a different object. A pointer can be made to point to something else (unless you pass in an ObjectType* const
pointer, which is pretty rare).
overload resolution might be a factor. For example, making operator overloads work naturally was one of the motivations for adding references to C++.
Upvotes: 2