On Sun, 10 Feb 2008 18:55:56 +0000, Leon wrote:
> On Sun, 10 Feb 2008 19:46:31 +0100, Alf P. Steinbach wrote:
>
>> * 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
>
> You think casts are useless? Then I want you to read some integers from
> a fstream, since fstream's read method returns chars only. In some cases
> you are right, and is a cast stupid. But maybe it works for this case.
> And if i say something wrong, please explain me my mistake, and don't
> respond so unkind. Or do you want to say you never make mistakes?
>
> Grz, Leon
By the way, this was to mr. Alf P. Steinbach, not to anyone else.