I am not sure what is wrong with this (keep in mind I'm kinda sorta new to C++)
I have this class:
Foo
{
string name;
public:
SetName(string);
}
string Foo::SetName(string name)
{
this->name = name;
return this->name;
};
//////////////////////////////////////////////
//This is where I am trying to return a Foo pointer from this global function:
Foo * ReturnFooPointer()
{
Foo foo;
Foo * foo_ptr;
foo_ptr = &foo;
return foo_ptr;
}
At compile time, this compiles just fine. However at run time it throws a runtime exception(Some sort of access violation)
What am I doing wrong?
We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.
When you create an object in any function it's destroyed as soon as the function execution is finished just like in variables. But when you return a object from a function firstly compiler creates a local instance of this object in heap called unnamed_temporary then destroyes the object you created.
You need to use the new keyword instead to create new Foo on the heap. The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory. Here is the correct code. Remember later to delete the pointer you are returning.
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
You need to use the new keyword instead to create new Foo on the heap.
The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory.
Here is the correct code.
Foo * ReturnFooPointer()
{
Foo * foo_ptr = new Foo();
return foo_ptr;
}
Remember later to delete the pointer you are returning.
So later in code:
Foo *pFoo = ReturnFooPointer();
//Use pFoo
//...
delete pFoo;
You're returning a pointer to a local object on the stack. It goes out of scope the moment your function returns, and is invalid.
You should create a new instance to return, i.e.,
Foo* foo_ptr = new Foo();
This will create an object in the heap and will live until you call delete
on it.
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