answersLogoWhite

0

Objects can be passed to functions in two ways: by value and by reference. You can also pass objects by pointer, but you should only use pointers when the object is an optional argument with a default of NULL. If an object is guaranteed to exist when making the call, the function should accept the object by value or by reference.

When you pass by value, the object's copy constructor is called automatically, and the copy is assigned to the function argument. The copy automatically falls from scope when the function returns. While this can be a useful feature, it is an expensive one. If the object is complex, with many embedded objects and/or derived from other classes of object, then their copy constructors are also invoked, which takes time and memory.

Passing by reference is more efficient as you are simply passing the address of the object. This is not unlike passing by pointer (indeed, Behind the Scenes that is exactly what occurs), but references are much easier to work with from a programming standpoint because they are guaranteed to be non-NULL, so there's no need to test for a NULL reference (unlike a pointer which must be explicitly tested before dereferencing).

To demonstrate the differences, consider the following minimal example, which includes three functions, byref, byval and byptr, and a simple class with trace code in the default constructor, copy constructor and destructor.

#include<iostream>

using namespace std;

struct X

{

X():data(42){

cout<<hex<<"X() [this="<<this<<"]"<<endl;

}

X(const X& src):data(src.data){

cout<<hex<<"X(const X& src) [this="<<this<<"] [src="<<&src<<"]"<<endl;

}

~X(){

cout<<hex<<"~X() [this="<<this<<"]"<<endl;

}

int data;

};

void byval(X src)

{

cout<<hex<<"byval(X src) [src="<<&src<<"]"<<endl;

src.data = 0;

}

void byref(X& src)

{

cout<<hex<<"byref(X& src) [src="<<&src<<"]"<<endl;

src.data = 1;

}

void byptr(X* src)

{

cout<<hex<<"byptr(X* src) [src="<<src<<"]"<<endl;

if( src != NULL )

src->data = 2;

}

int main()

{

cout<<"command: X x"<<endl;

X x;

cout<<dec<<"return: x.data="<<x.data<<'\n'<<endl;

cout<<"command: byval(x)"<<endl;

byval(x);

cout<<dec<<"return: x.data="<<x.data<<'\n'<<endl;

cout<<"command: byref(x)"<<endl;

byref(x);

cout<<dec<<"return: x.data="<<x.data<<'\n'<<endl;

cout<<"command: byptr(&x)"<<endl;

byptr(&x);

cout<<dec<<"return: x.data="<<x.data<<'\n'<<endl;

return( 0 );

}

Example output:

command: X x

X() [this=0023FA4C]

return: x.data=42

command: byval(x)

X(const X& src) [this=0023F958] [src=0023FA4C]

byval(X src) [src=0023F958]

~X() [this=0023F958]

return: x.data=42

command: byref(x)

byref(X& src) [src=0023FA4C]

return: x.data=1

command: byptr(&x)

byptr(X* src) [src=0023FA4C]

return: x.data=2

~X() [this=0023FA4C]

The hex values show the memory addresses of the indicated variables. Note that in the call to byval, the copy constructor is invoked before the function body executes and the copy is destroyed automatically when the function returns. Since it worked on a copy of x, x was left unaffected by the function, thus it still holds the value 42 (assigned by the default constructor). Note also that byptr must check for NULL before dereferencing the pointer. Of the three, byref is the most efficient and easiest to program.

Note that when a function should not intentionally alter the immutable members of the object passed to it, the argument must be declared const. The copy constructor is a typical example of this; after all, the copy constructor only needs to copy the object's members, it must not alter it in any way. Constant references not only prevent the programmer from inadvertently changing the object (and thus eliminating bugs that might otherwise go undetected), it also assures the caller that the object will not be altered when the function returns.

If a function does alter an object, but you do not wish those changes to be reflected in the original object, but you'd still like to know what those changes were, copy the object and pass the copy, then compare the copy with the original. Do not use pass by value for this because the automatic copy is local to the function and will fall from scope when the function returns.

Pass by value has its uses, but passing objects by value is rarely one of them as it generally serves no useful purpose to copy an object. There are exceptions, of course, but always think carefully about why you are passing by value; what purpose does the automatic copy serve? Get into the habit of always passing objects by reference or constant reference, and only pass by value when there is a valid reason for doing so. And, of course, comment your function clearly to explain the reason.

User Avatar

Wiki User

12y ago

What else can I help you with?

Related Questions

Explain linear search with an example?

Sequential search of an object with in an array of objects is called as linear search.


What is an example of two objects in your life that are interdependent?

An example of two objects in my life that are interdependent are my phone and charger. The phone requires the charger to be recharged and the charger requires the phone to be connected in order to function. Both objects rely on each other to fulfill their intended purpose.


What is the discernibility argument?

The discernibility argument is an argument used in philosophy, especially in theories of identity. It posits that if two objects are truly identical in all respects, then they cannot be thought of as distinct entities—there must be some discernible feature that sets them apart. This argument is often applied to questions of personal identity and the nature of objects.


What Pronouns in the objective case may function as?

Pronouns in the objective case can function as direct objects, indirect objects, and objects of prepositions in a sentence.


Are gerunds indirect objects or object of the prepositions?

Gerunds can function as objects of prepositions. When a gerund is used after a preposition, it serves as the object of that preposition. For example, in the sentence &quot;I am good at dancing,&quot; &quot;dancing&quot; is a gerund that functions as the object of the preposition &quot;at.&quot;


What is a function of the magnifying glasses?

The function of magnifying glasses are to magnify certain small objects if necessary to see the world in a better way. An example would be to use it to examine an ant crawling into its ant hole.


Which is the function which destroys objects in C?

No objects in C. For C++, it is destructor.


What is the study of the design form and function of objects in the real world?

what is the study of the design, form and function of objects in the real world


What is function of drill?

The function of a drill is make clean holes in objects.


How do you explain the apparent weightlessness of orbiting objects?

you cant


Explain how objects are created in Java?

with new operator


What are the examples of referential function of language?

Examples of the referential function of language include stating facts, describing objects, events, or places, providing information, and identifying people or things. This function is used to convey information and communicate specific details about the world around us.