J Doe.
J Doe.

Reputation: 349

C++ Overriding virtual function with different return type

I was very surprised just now to see that this code (paraphrased) built.

class Foo
{
  protected:
     virtual bool CheckThis(int id);
}

class Bar : public Foo
{
  protected:
     virtual tErrorCode CheckThis(int id, char something);
};

I thought it was not possible to override a function with a different return type? Somehow this built. OS is vxworks.

Upvotes: 1

Views: 4343

Answers (3)

R Sahu
R Sahu

Reputation: 206627

I thought it was not possible to override a function with a different return type?

Yes, it is possible, but with some constraints.

In particular, you can't use any type you want, only a covariant type can be used.

In addition, the argument types must be the same, otherwise it is not an override.

Example:

class type1 {};
class type2 : public type1 {};

class Foo {
   protected:
      virtual type1& CheckThis(int id);
}

class Bar : public Foo
{
   protected:

      // This is not an override, it is an overload.
      virtual type2& CheckThis(int id, char);

      // This is an override.
      virtual type2& CheckThis(int id);
};

Upvotes: 2

Viktor
Viktor

Reputation: 1054

Since C++11, you should use the special override keyword. It allows the compiler to check if the base class has a method for the derived class to override.

Live example

class Foo 
{
  protected:
     virtual bool CheckThis(int id);
}

class Bar : public Foo
{
  protected:
     tErrorCode CheckThis(int id, char something) override; // error:  marked 'override', but does not override
};

Moreover, since you override a base class method, the virtual keyword is not required in the derived class. The base method is virtual, so the overriding method is implicitly virtual.

Upvotes: 0

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

In fact, this method:

virtual tErrorCode CheckThis(int id, char something);

Does not override anything, because it has a different signature from this method:

virtual bool CheckThis(int id);

Note, that you might use the override specifier to ensure that the method in the derived class actually overrides the method of the base class.

So, this piece of code:

class Foo {
  protected:
     virtual bool CheckThis(int id);
};

class Bar : public Foo
{
  protected:
     virtual tErrorCode CheckThis(int id, char something) override;
};

Will not compile, but this one will:

class Foo {
  protected:
     virtual bool CheckThis(int id);
};

class Bar : public Foo
{
  protected:
     virtual bool CheckThis(int id) override;
};

Upvotes: 6

Related Questions