0

I can't actually figure out what I'm doing wrong here.

So basically I have an object pointer which I pass unto a function to set its value to point to a new Object instance but it doesn't seem to work and I can't resolve why. Below is a code sample of what I'm trying to do.

 GetPointer(Object *pointer){
     pointer = new Object();
 }

 in main:

 Object *pointer;
 GetPointer(pointer);

I also tried initializing the pointer right away and that works so I really can't understand what's wrong with the code above. Any suggestions?

   Object *pointer = new Object(); 
3
  • 1
    A pointer is nothing special. Replace Object* with int and you'll understand why it works the way it does. Commented Aug 20, 2015 at 11:14
  • " to set its value" - no, it doesn't. Without a reference, a second level of indirection (pointer-to-pointer), or simply using your function return value, all you're setting is the value of the automatic variable, not the caller's pointer. Commented Aug 20, 2015 at 11:16
  • I see. I thought it was the same outcome when I transform the initialization into a function. Commented Aug 20, 2015 at 11:18

2 Answers 2

9

You should pass your pointer by reference

void GetPointer(Object *&pointer)
{
     pointer = new Object();
}

Object *pointer;
GetPointer(pointer);

or just return pointer:

Object* GetPointer()
{
     return new Object();
}

Object *ptr = GetPointer();

or better:

std::unique_ptr<Object> GetPointer()
{
     return std::unique_ptr{new Object()};
}

auto ptr = GetPointer();
Sign up to request clarification or add additional context in comments.

2 Comments

Or one another method often seen in combination with COM interfaces are pointer to a pointer like in void GetPointer(Object** PtrToObject).
Works like a charm. Thanks a lot. Though, I'm avoiding returns as I'm following a style where outputs should be redirected to pointers.
0

I think you should return the pointer from inside the function GetPointer. Like any other function, every argument will be destroid when finish. And returning the pointer will make your function more meaningful, because its name has "get" on it.

Comments

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.