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 no
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.