Override a member function with different return type

后端 未结 5 1066
臣服心动
臣服心动 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:33

    Overriding essentially means that either the Base class method or the Derived class method will be called at run-time depending on the actual object pointed by the pointer.
    It implies that:
    i.e: Every place where the Base class method can be called can be replaced by call to Derived class method without any change to calling code.

    In order to achieve this the only possible way is to restrict the return types of the overriding virtual methods to return the same type as the Base class or a type derived from that(co-variant return types) and the Standard enforces this condition.

    If the above condition was not in place it would leave a window to break the existing code by addition of new functionality.

提交回复
热议问题