"David Sobey" <ds****@NOSPAMu grad.unimelb.ed u.au> wrote in message
news:42******@d news.tpgi.com.a u...
No way!! if it executes the derived class function, which states
explicitly the return type is DerivedClass*, it will HAVE to return a DerivedClass*!
Man this driving me mad! I so nearly solved this thing. lol. Are you sure
this can't be achieved? Please?!
The function does return a DerivedClass*, but you receive it as a BaseClass*
because that's the return type of the function you called. What you seem to
want doesn't really make sense. Consider the following:
// ignore all the memory leaks
void f(BaseClass *p)
{
BaseClass *q = p->me();
}
int main()
{
f(new BaseClass);
f(new DerivedClass);
}
For the first call of function f, BaseClass::me will be called inside the
function and return a BaseClass*. For the second call DerivedClass::m e will
be called and return a DerivedClass*. You can see that the function f only
knows that 'p' points to a BaseClass or a class derived from it, and the
actual class of the object that 'p' points to can vary from one call to
another. It obviously can't assume that it's going to receive a
DerivedClass* from the call to me() because that will only happen when 'p'
really points to a DerivedClass, and that's not necessarily the case. If it
knew that then it could change its parameter type:
void f(DerivedClass *p)
{
DerivedClass *q = p->me();
}
Now it knows that 'q' points to a DerivedClass object, or an object of a
class derived from DerivedClass, but you can't call it with any old
BaseClass* now.
If you always knew which class's virtual function would be called at a given
statement in your code, there would be no need for the function to be
virtual. Virtual functions are only useful when you don't know which one
will be called until run-time.
DW