James Wierzba
James Wierzba

Reputation: 17548

Best way to overload a function based on argument type being pointer | reference?

I have a function like so:

void myFunction(MyObject& obj)
{
    //lots of code to operate on obj
}

My issue is that sometimes obj will be a pointer to an instance of the type MyObject

void myFunction(MyObject* obj)
{
    //...
}

My question is how can I achieve having both function definitions, while not having to repeat any code?

Upvotes: 1

Views: 63

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

You can simply forward the instance on from the pointer function.

void myFunction(MyObject* obj)
{
    if (obj != nullptr) // do not want to dereference a null pointer
        myFunction(*obj);
}

Will call the reference version of myFunction allowing you to only maintain one function.

This assumes that you only need to work with the value of the object and using a pointer or reference is to just save having to copy the object.

Upvotes: 5

Related Questions