Sorry for asking all these pointer questions :P but...

Is this correct?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class exampleClass
{
public:
exampleClass();
type * returnAPointer(); //pretend type is an object/datatype
private:
type Pointer;
};
...
type * exampleClass::returnAPointer()
{
...
return Pointer;
}

What I am really asking is: is this the right way to write a function that returns a pointer? Can you write a function that returns a pointer? It would be great if I could, if i can't I will have to go back to the drawing board to solve this problem :D
Last edited on
no.

"Pointer" is of type "type" as is illustrated on line 7:

type Pointer;

The name "Pointer" is actually a misnomer because it isn't a pointer. It's an object of type "type".


So when you return Pointer on line 13:

return Pointer;

You are returning type type, which does not match the function's specified return type of type* (aka: a pointer to type).


If you want to obtain the address of 'Pointer', you can use the 'address of' operator (&):

 
return &Pointer;


Since 'Pointer' is of type type,
That means '&Pointer' is of type type*.
Which matches the specified return type of the function.


(This would be less ambiguous/confusing to explain if you chose names other than 'type' and 'Pointer' =x)
Typo... i meant type * pointer
In that case, yes. That is syntactically correct.

However, what does 'Pointer' point to?
But does that mean that I can put for the function that returns the pointer:
1
2
3
4
5
type * exampleClass::ReturnAPointer()
{
...
return &(something of type type)
}

then later put
1
2
type * myPointerLater;
myPointerLater = exampleInstance.ReturnAPointer();

Yes... that would be syntactically legal.

However... again... when dealing with pointers you have to be sure that the data you're pointing to actually exists.

[Bad] Example:

1
2
3
4
5
int* func()
{
    int foo = 5;
    return &foo;
}


This is syntactically legal... but it is incorrect code. We are returning a pointer to foo... yet foo will cease to exist as soon as the function exits. So we are effectively returning a bad pointer.
Topic archived. No new replies allowed.