Re: Covariant return types doesn't work (with g++ 4.1.2)
On Feb 11, 9:16 am, James Kanze <james.ka...@gmail.com> wrote:
On Feb 10, 7:57 pm, "Alf P. Steinbach" <al...@start.no> wrote:
* Thomas J. Gritzan:
mr.xiaofan...@gmail.com wrote:
class virt_base
{
[...]
virtual virt_base* cut()
{
returnnew virt_base();
}
[...]
};
class virt_derived
: public virt_base
{
[...]
virtual virt_derived* cut()
{
returnnew virt_derived();
}
[...]
};
Thecovariantreturntypelets you override a function with
a more strict function, i.e. a function returning a derived
type. However,typechecking is done at compile time, so
your compiler has to know, that the object you are calling
cut() on is a virt_derived.
int main()
{
virt_base* my_virt_derived = new virt_derived();
Change this to
virt_derived* my_virt_derived = new virt_derived();
That would make the code compile, but would defeat the pupose
of the code.
What is the purpose of the code? (That's meant to be an honest
question. As far as I can tell, co-variantreturntypes are a
solution looking for a problem---I've yet to find any reasonable
use for them.)
--
James Kanze (GABI Software) email:james.ka...@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34
Thanks for you and all replies - The purpose of the code was,
originally, to assign a member v-func that() to each classes which I
would like to get a pointer of THAT particular type when using them. I
did it like
...
virtual derived* that()
{
return this;
}
virtual const derived* that() const
{
return this;
}
and wished it return a derived* pointer which I could dereference to
the full-sized object rather than being sliced to base. I implemented
a generic pool-based container which can copy&store polymorphic
objects and it works well - but I need to know which is which when I
pull them out of the container, thus the idea of using covariant
return types.
If I have to rely on a downcast to get the correct pointer, IMHO I am
not using cov return types at all - I still have to know (at compile
time) which object I am going to cast it. I currently use member flags
to identify this and set up if-else if cascade, which is ugly; I
thought cov return types could resolve this nicely but found out it
didn't work.
Any more thoughts on this?