Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing pointers and references in function definition in C++ [closed]

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?

like image 606
Chiel Avatar asked Aug 04 '15 11:08

Chiel


People also ask

What are pointers and reference in C?

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.

Can pointers be passed by reference?

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.

Why are references used over 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.


2 Answers

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);
like image 156
Quentin Avatar answered Sep 20 '22 04:09

Quentin


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);
like image 45
Kasim Rangwala Avatar answered Sep 20 '22 04:09

Kasim Rangwala