I have this problem:
void myFunc()
{
MyClass * myInstance = NULL;
newInstance(myInstance);
}
void newInstance(MyClass * instance)
{
instance = new MyClass(...);
}
the code seems to work fine, but when I exits from newInstance function, my myInstance is null and not with the values that have inside newInstance… where is the problem?t
thanks
The pointer is copied into
newInstanceand then you change the value of that copy. If you want to modify the pointer inside the function, you need to pass it by reference:Or alternatively, you could pass a
MyClass**and do*instance = new Class(...);.Either way, it would be preferable to actually return the pointer instead of passing it as a modifiable argument.
Of course, you will have to remember to
deletethe object. To avoid this, you can make it safer by using smart pointers: