D
David White
David Sobey said:Hi everyone
I'm having huge difficulties overriding a virtual function with a function
that returns a covariant type. I'd be grateful if someone could show me some
code where this is done:
- A class BaseClass is declared with a function me() that takes no arguments
and returns itself, or a pointer or reference to itself.
- A derived class DerivedClass that override me() that takes no arguments
and returns itself, a pointer or reference to itself ("itself" being the
instance of the derived class)
- A piece of code like this: (Warning: this is PSUEDOCODE)
BaseClass foo=new DerivedClass
This will have to be:
BaseClass *foo = new DerivedClass;
foo.me() <-this should return a pointer or reference or instance of type
foo->me();
DerivedClass.
Since foo is a pointer to a BaseClass, foo->me() will return a BaseClass*.
However, that BaseClass* will point to a DerivedClass object.
I would be VERY VERY gratefull if someone could help me with this
confounding problem, be it in C++ or C#.
You won't get any C# in this place, but here is a C++ example:
class BaseClass
{
public:
virtual BaseClass *me() const { return new BaseClass(*this); }
// more members
};
class DerivedClass : public BaseClass
{
public:
DerivedClass *me() const { return new DerivedClass (*this); }
// more members
};
int main()
{
BaseClass *foo = new DerivedClass;
BaseClass *p = foo->me(); // p points to a DerivedClass object
}
It is the convention to name such a virtual function 'clone' rather than
'me'.
DW