Monday, July 27, 2009

Passing down objects(or pointers to them) to functions in C++?

I was wondering if it was possible to pass down either an object itself directly to a function or if I could make a pointer to an object to pass down.





Example:





testFunction(object object_name);


--or--


testFunction(object *object_pointer);





If you need me to rephrase the question, just ask. Thanks.

Passing down objects(or pointers to them) to functions in C++?
testFunction(object object_name) is possible but requires that object has a copy constructor if it is a class or struct.





testFunction(object *object_pointer) requires the caller to call the function as testFunction(%26amp;object_instance) and requires more effort in the function body.


To reference the object class, you must use object_pointer-%26gt;data or object_pointer-%26gt;function() or *object_pointer





testFunction(object %26amp;object_reference) is the recommended way to pass an object. In the function body, you just type object_reference.data or object_reference.function() to access the data and functions in the object class.


To prevent the function from returning a modified object,


use testFunction(const object %26amp;object_reference)
Reply:testFunction(object object_name) - you are passing the copy of the object, not the object itself.





testFunction(object%26amp; object_name) - now you are passing the actual object (its reference to be precise).





testFunction(object* object_name) - now you are passing the pointer to that object.





Changes made in the last two examples will affect the original object that was passed to the method. In the first example you are passing the copy, so the changes will not affect the original object.
Reply:You should use a reference to the object in question. The only way to pass an object by value is to implement a copy constructor, and then a new object would be instantiated in the stack of the called function. There is a lot of overhead associated with this, and it's generally unnecessary.





So in your calling function you would have:


testFunction( %26amp;myObject );





And your function would look like:


void testFunction( Object* theObject ){}


No comments:

Post a Comment