Group: comp.lang.c++
From: "Alf P. Steinbach"
Date: Sunday, February 10, 2008 12:46 PM
Subject: Re: Covariant return types doesn't work (with g++ 4.1.2)

* Leon:
> On Sun, 10 Feb 2008 10:01:47 -0800, mr.xiaofan.li wrote:
>
>> Hi,
>>
>> I have been totally confused about the covariant return type feature in
>> C++. Below is an example code I wrote that doesn't compile with g++
>> 4.1.2 (on Fedora 8)
>>
>> class virt_base
>> {
>> public:
>> virt_base()
>> {
>> }
>>
>> virtual ~virt_base()
>> {
>>
>> }
>>
>> virtual virt_base* cut()
>> {
>> return new virt_base();
>> }
>>
>> void say_hi()
>> {
>> cout <<"hi!!! " <>> }
>> };
>>
>> class virt_derived
>> : public virt_base
>> {
>> public:
>> virt_derived()
>> {
>> }
>>
>> ~virt_derived()
>> {
>>
>> }
>>
>> virtual virt_derived* cut()
>> {
>> return new virt_derived();
>> }
>>
>> void say_hi()
>> {
>> cout <<"HI!!!! " <>> }
>> };
>>
>> int main()
>> {
>> virt_base* my_virt_derived = new virt_derived(); virt_derived*
>> new_virt_derived = my_virt_derived->cut(); // g++
>> complains here: invalid
>> //
>> conversion from 'virt_base*' to
>> //
>> 'virt_derived*'
>> new_virt_derived->say_hi();
>> }
>>
>> ------------
>> It is very weird. Can somebody enlighten me what went wrong here? Thanks
>> in advance.
>
> try changing your main() to this:
>
> int main()
> {
> virt_base* my_virt_derived = new virt_derived();
> virt_derived* new_virt_derived = (virt_derived*)my_virt_derived-
>> cut();

To the OP:

Don't follow that advice.

Casts can often make code compile, at the expense of most often being
incorrect, and hiding future errors.

The cast says "I know what I'm doing", when that is absolutely not so.

In short the above is extremely bad advice: it is advicing you to lie
and bluff your way.

Don't pay any heed to folks who think a cast (and especially a C style
cast) is a solution.

They simply don't know anything about what they're talking about.


> }


Cheers, & hth.,

- Alf

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?