I have a function that has two instances of classes as arguments:
void cookPasta(const Tomato& tomato, const Meat* meat)
{
if (meat != nullptr)
cookPastaWithMeat(tomato, *meat);
else
cookPastaWithoutMeat(tomato);
}
As the function shows, an instance of Tomato
is always required, whereas Meat
is optional and a nullptr
can be passed instead. I do this to allow the cookPasta
function to be called even if the user has never declared an instance of the Meat
class.
Is it bad practice to mix references and pointers in the function signature?
To store a reference is to store an address in the memory of a variable. A pointer is a variable itself and has a value whereas a reference only has a variable that it is referencing.
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
The one thing you lose with this approach is the possibility to pass in a temporary Meat
, as its address can't be taken.
Why not use overloading, by simply renaming cookPastaWithMeat
and cookPastaWithoutMeat
?
void cookPasta(const Tomato& tomato, const Meat& meat);
void cookPasta(const Tomato& tomato);
Your Practice is good
const
keyword.But, 2nd parameter pointer
can be little better using optional parameter feature
of C++. check out here.
void cookPasta(const Tomato& tomato, Meat* meat = nullptr)
{
if (meat != nullptr)
cookPastaWithMeat(tomato, *meat);
else
cookPastaWithoutMeat(tomato);
}
Now, Call the same function in both way.
cookPasta(tomato); // meat will default to nullptr
cookPasta(tomato, meat);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With