Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Passing address of copy of local object to pointer to base class

Hi,
Can I pass the address of a copy of a local object to a pointer? Say function someFunc(), of a container class L returns a copy of a local object of type X. X is derived from the ABSTRACT class Y.

X L::someFunc()
{ X local;
// rest of code
return X;
}

How can I pass the object returned to a pointer of abstract class Y, that is, say:
L Lobject;
Y* Yptr = &(Lobject.someFunc());

If I do the above I get the compiler error:
'&': illegal operation on bound member function expression

I wonder if anyone can offer a solution. All help will be greatly appreciated.
[842 byte] By [ray] at [2007-11-11 7:56:24]
# 1 Re: Passing address of copy of local object to pointer to base class
Take a look at this article about the use of a pointer to a function:

http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=140&rl=1

without the creation of a void pointer which you might then cast as being a pointer to a Y object you run into binding problems.
nspils at 2007-11-11 21:01:44 >
# 2 Re: Passing address of copy of local object to pointer to base class
You can't do that. The local copy returned from the function is actually a temporary object. The only safe thing you can do with it is copy it to another object:

Y Yobj = Lobject.someFunc();

The problem of course is that Yobj doesn't have the same type as the object returned from someFunc. So if you want to obtain a refererence or a pointer *safely*, make sure that someFunc returns the address of its container's object, not something created inside someFunc() itself:

Y * someFunc (int idx)
{
return &collections[idx];
}

Alternatively:

Y & someFunc (int idx)
{
return collections[idex];
}
Danny at 2007-11-11 21:02:45 >