Differing return type for virtual functions

前端 未结 4 531
余生分开走
余生分开走 2020-12-19 01:20

A virtual function\'s return type should be the same type that is in base class, or covariant. But why do we have this restriction?

4条回答
  •  心在旅途
    2020-12-19 02:18

    According to C++ Standard:

    The return type of an overriding function shall be either identical to the return type of the overridden func- tion or covariant with the classes of the functions. If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria:

    1) both are pointers to classes or references to classes

    2) the class in the return type of B::f is the same class as the class in the return type of D::f, or is an unambiguous and accessible direct or indirect base class of the class in the return type of D::f

    3) both pointers or references have the same cv-qualification and the class type in the return type of D::f has the same cv-qualification as or less cv-qualification than the class type in the return type of B::f.

提交回复
热议问题