Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

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

Status
Not open for further replies.

raydona

Programmer
May 12, 2005
27
GB
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.
 
A function returns a value, not a variable. It's impossible to get an address of a value (for example, you can't write &1).
You may dynamically allocate an object of X in someFunc member function and return a pointer (Y*) to it, but you must delete this object by hand in callee context (it's error-prone approach, of course). Or use some kind of a smart pointer to deallocate this pointer safety at proper context.
 
Code:
L Lobject;
X Xobj = Lobject.someFunc();
Y* Yptr = &Xobj;
 
I think, explicit declaration of X class temp var makes advantages of polymorphism too weak. If we must know exact type of returned value, why we have interface pointer to Y after that?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top