1

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?

2
  • I am not sure. Personally I would settle for one or other. Then, if needed, pass in &rObject or *pObject. That has worked for me. Commented May 23, 2016 at 17:47
  • You can always call one function from the other, but I don't think you really need two, the caller can provide either easily. Commented May 23, 2016 at 17:49

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Cool. I was not sure that would compile. But my comment implies something similar. But you did better. 😀
I would check for nullptr first before forwarding to the reference version of myFunction.
@PaulMcKenzie Good suggestion. I added a check into the code.
Wouldn't it be easier to do it the other way around? From the reference function to the pointer function, since a reference cannot be ever null, no checkings would be required...
@LoPiTaL You would still need the null check in the pointer version as the OP has values and pointers so I don't think it matters. Plus the OP already has the code in the reference version so I did not want to change that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.