I have a variable that is an object :
Foo x;
And I need to call a function that requires a Foo*. How can I convert from Foo to Foo*.
I know this wont work :
Foo* y = &x;
o->setFoo(y);
Because "x" is a local variable, so it will be destroyed and the pointer I gave will point to nothing.
How can I do ?
Note : I can't modify the function or the type of the variable a !
If the appropriate copy constructor is defined,
o->setFoo(new Foo(x));
But then o
's destructor should delete x
(and setFoo
probably should too if it'.\s already set).
Note: defining a destructor is not enough.
The copy constructor/assignment operator also need to be defined and:
See Rule of 4 for explanation.
If you can't touch the class definition of o
at all, then you'll need to be very careful about the memory allocation/deallocation so you don't leak memory.
You should allocate on the heap with the new
keyword:
Foo* y = new Foo;
o->setFoo(y);
though you will need to manage the deletion of the Foo later on, otherwise you get memory leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With