Using subclass type parameters in virtual functions

后端 未结 4 1274
甜味超标
甜味超标 2021-02-05 13:15

I have this piece of code (contrived from my real-life trouble)

It cannot compile, complaining ExtendsB does not implement B::Run(A* a). However, it has no

4条回答
  •  温柔的废话
    2021-02-05 13:51

    The error is pretty clear: You need void Run(A*) in your class ExtendedB, but you don't have that. All you have is void Run(ExtendedA*), but that's not the same: The base class promises to accept any A-pointer, but your ExtendedB::Run is pickier and only accepts a narrow subset.

    (You're confusing covariance and contravariance, but that is not relevant for C++, since C++ does not allow contravariant overrides.)

提交回复
热议问题