16

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?

Chiel
  • 6,006
  • 2
  • 32
  • 57

3 Answers3

30

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);
Quentin
  • 62,093
  • 7
  • 131
  • 191
8

Your Practice is good

  • You've used const keyword.
  • Passing reference
  • 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);
Community
  • 1
  • 1
Kasim Rangwala
  • 1,765
  • 2
  • 23
  • 44
  • 8
    Except you _can't_ call the same function "in both way" without breaking symmetry. You probably meant `cookPasta(tomato, &meat);`, assuming sensible types at the callsite. Do you see now why this is _not_ good practice? – Lightness Races in Orbit Aug 04 '15 at 12:06
4

It's good practice since you have a good reason for doing so: a pointer can be nullptr whereas a reference must always be passed. You are exploiting this elegantly.

Using const means that the function cannot modify the parameters passed from the caller; that's good too.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 3
    It's hardly elegant. You're mixing levels of indirection for objects that, semantically, are both to be treated _as_ their base objects rather than as handles. Symmetry is broken and surprise is generated. – Lightness Races in Orbit Aug 04 '15 at 12:07
  • Symmetry is little more than an idealism irrationally desired by physicists. – Bathsheba Aug 12 '15 at 12:36