I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++.
Do I need to pass pointers, references, or non-pointer and non-reference values? I remember in Java there are no such issues since we pass just the variable that holds reference to the objects.
It would be great if you could also explain where to use each of those options.
Pass by value, except when
const
reference,const
lvalue reference,const
reference or not.)Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional
(boost::optional
for older std libs), and aliasing is done fine by reference.
C++11's move semantics make passing and returning by value much more attractive even for complex objects.
Pass arguments by const
reference, except when
const
referenceNULL
/0
/nullptr
instead; apply the previous rule to determine whether you should pass by a pointer to a const
argument(here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)
There's more to this, but these few beginner's rules will get you quite far.