Override a member function with different return type

后端 未结 5 1064
臣服心动
臣服心动 2020-12-01 12:16

Consider the example below:

#include 

using namespace std;

class base
{
   public:
      virtual int func()
      {
         cout <<          


        
5条回答
  •  悲哀的现实
    2020-12-01 12:56

    In order to override a virtual function, the return value must be exactly the same*. C++ will not automatically convert between double and int here - after all, how would it know what return type you want when calling from a derived class pointer? Note that if you change part of the signature (parameters, const-ness, etc), then you can change the return value as well.

    * - strictly speaking, it must be 'covariant'. What this means is that the type you return must be a subset of the parent function's return type. For example, if the parent class returns a base *, you could return a derived *. Since deriveds are simultaneously also bases, the compiler lets you override in this manner. But you can't return totally unrelated types such as int and double; just because there's an implicit conversion doesn't mean the compiler will let you do this kind of override.

提交回复
热议问题