Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return class pointer from a function

Tags:

c++

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?

like image 439
theKing Avatar asked Apr 21 '09 17:04

theKing


People also ask

Can we return pointer from a function?

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.

Can we return a class from a function?

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.

How do you return a pointer object from a function in C++?

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.

How does a function return a pointer value?

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.


2 Answers

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;
like image 138
Brian R. Bondy Avatar answered Oct 14 '22 02:10

Brian R. Bondy


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.

like image 35
Michael Avatar answered Oct 14 '22 03:10

Michael