1

If I have class* object = NULL;, and I pass object into function(class* arg){arg = new class();}, does object = new class()?

I ask because a pointer is just an address, right? So if I pass a NULL pointer as an argument and assign a new object to it, the address will be changed from zero, and the original pointer will not point to the new object, correct?

2 Answers2

2

Inside the function, arg will point to the new object; but as you passed a copy of the pointer, once the function is over, it will not be accessible anymore, and object will not point to it (but still to NULL).

You need to pass either a reference to object (class*&), or a pointer to object (class**), to enable the function to modify it,

Aganju
  • 6,295
  • 1
  • 12
  • 23
0

That's correct. You passed object by value to the function. So changing the value in the function has no effect on object. If you wanted the function to be able to change object, you need to pass either a reference or a pointer to object to the function.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278