Reputation: 1837
Can someone explain what this actually represents ?
Foo *getfoo()
{
return foo_object;
}
Foo
here is a class.
My question is what does the pointer before the function name represents?
Upvotes: 0
Views: 173
Reputation: 35970
As others noted, 'Foo *' syntax means function is returning a pointer to a place in the memory, not an object itself.
It has the implications that, if you get this pointer, this means getfoo() could've allocated memory for it. Thus it's possible you will have to free it yourself, otherwise this memory will be allocated for the whole time your program is running. This is called a memory leak.
Here is an example with freeing memory:
class Foo {};
Foo *getfoo() {
Foo *f = new Foo(); // Memory allocated here
return f;
}
int main () {
Foo *g = getfoo();
// some code here
delete(g); // free the memory as "g" is no longer needed.
return 0;
}
In C++ it's crucial that you learn to manage memory. Otherwise, sooner or later, your apps will fail. There are some programming patterns helping with that, of which the most popular is smart pointers.
Upvotes: 1
Reputation: 67301
It means that the function returns a pointer.
and what type
that pointer is what is mentioned before the pointer.
that is the pointer will be of type Foo
.Foo
here is as you said is a class
and the function returns a class object pointer.
Upvotes: 1
Reputation: 5852
Some people like to add the asterisk right before the name. I personally prefer this syntax:
Foo * getfoo () {
return foo_object;
}
I think that shows a bit more clearly that Foo *
is just the type the function returns (just like it could be int
).
Upvotes: 1