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.
Rules of thumb for C++11:
Pass by value, except when
constreference,constlvalue reference,constreference or not.)Passing by pointer is virtually never advised. Optional parameters are best expressed as a
std::optional(boost::optionalfor 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.
Rules of thumb for C++03:
Pass arguments by
constreference, except whenconstreferenceNULL/0/nullptrinstead; apply the previous rule to determine whether you should pass by a pointer to aconstargument(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.