I'm having trouble passing objects to other functions. What are the guidlines for passing objects? Thanks.
I'm having trouble passing objects to other functions. What are the guidlines for passing objects? Thanks.
What does the function do to the object?
Kuphryn
Basically, just past the reference to the object as the function prototype below indicates
Code:returnValue myFunction( MyObject &object ); // If you need to modify object returnValue myFunction( const MyObject &object ); // If you don't modify object
source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense
If you are trying to pass an object without the & symbol (by reference) and without the * (as a pointer) then you are trying to pass it as value. This requires a copy to be made, so the class must have a copy constructor. This is a bad practice though because it causes a duplication of the object, which is time consuming and eats the stack.
Theres no need to pass it as const reference just pass the class by value.
Code:class test { public: int yep; }; void function(test hello); int main() { test brian; brian.yep = 10; function(brian); std::cout<<brian.yep; std::cin.get(); } void function(test hello) { hello.yep = hello.yep + 10; std::cout<<hello.yep; }
Last edited by prog-bman; 10-06-2004 at 09:50 AM.
Woop?
>> Theres no need to pass it as const reference just pass the class by value.
As mentioned by pablo, pass by value requires a copy to be made. An object tends to be large in size (larger than primitive types i.e. int). So it'd be better if you pass the reference and add 'const' so that the object's member data is retained in a function.
source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense