Why is there no parameter contra-variance for overriding?

后端 未结 6 1163
借酒劲吻你
借酒劲吻你 2020-12-02 20:36

C++ and Java support return-type covariance when overriding methods.

Neither, however, support contra-variance in parameter types - instead, it translates to overl

6条回答
  •  眼角桃花
    2020-12-02 21:29

    For C++, Stroustrup discusses the reasons for hiding briefly in section 3.5.3 of The Design & Evolution of C++. His reasoning is (I paraphrase) that other solutions raise just as many issues, and it has been this way since C With Classes days.

    As an example, he gives two classes - and a derived class B. Both have a virtual copy() function which takes a pointer of their respective types. If we say:

    A a;
    B b;
    b.copy( & a );
    

    that is currently an error, as B's copy() hides A's. If it were not an error, only the A parts of B could be updated by A's copy() function.

    Once again, I've paraphrased - if you are interested, read the book, which is excellent.

提交回复
热议问题