You are here:

C++/doubt in function argument passing


1."Pass by value , Pass by reference ,Pass by address in these 3 types of parameter passing, which of them will create new objects?"

2. Can you explain each one, when i have to use based on scenarios?

Only pass by value creates a new object of that type. Pass by address passes a copy of the address, and pass by reference is semantically equivalent to creating and passing an alias for the original object.  

In general, if the parameter being passed has a small size and is inexpensive to copy (for example an int or a small object which contain one or two members which are built in types), and you are not passing a derived class object, pass by value is preferred.

Pass a pointer to a function when the object pointed to might not exist - that is, you pass a pointer when you are giving either the address of a real object or 0 (NULL). It is the responsibility of the recipient function to test the pointer for validity before dereferencing it. You would also pass a (ideally smart) pointer to a function if the original object was allocated with a new.

In all other cases, prefer passing by reference. The reasons are performance (avoid creating a new object) and to preserve polymorphism, as well as to indicate that the object is guaranteed to exist. In general, pass a parameter by const reference. Pass by a non-const reference only when the function is expected (or encouraged) to modify the original object which is guaranteed to exist. For example,

void boo( const bar& in_param, baz& out_result ) ;  


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2017 All rights reserved.