Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function overriding with different return types

Does the return type influence on function overriding? (As far as I know return typde is not a part of a function/method signature) In a base class I have a function, which doesn't get arguments, returns int and is pure virtual. In each derived class, I define an enum for the return type.The function is overridden in the derived classes, i.e. it has the same signature but different behavior. The question is: Is that legal for overriding and return type is not a part of function overriding?

Code example:

class Base
{
  public:
  typedef int ret;
  virtual ret method() = 0;
};

class Der1
{
public:
  enum ret1{
    ret1_0,
    ret1_1
  };
  ret1 method() { return ret1_1;}
};

class Der1
{
public:
  enum ret2{
    ret2_0,
    ret2_1
  };
  ret1 method() { return ret2_0;}
};
like image 879
Yakov Avatar asked Feb 25 '13 09:02

Yakov


1 Answers

You can override functions with different return types but only covariant return types are allowed.

Function Overriding 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 so the Standard enforces this condition.

Without this condition the existing code will break by addition of new functionality(new overriding functions).

like image 160
Alok Save Avatar answered Nov 14 '22 09:11

Alok Save