Virtual functions and polymorphism

后端 未结 6 1180
一向
一向 2021-01-24 00:33

Suppose I have this:

class A
{
    public:
    virtual int hello(A a);
};

class B : public A
{
   public:
   int hello(B b){ bla bla };
};

So,

6条回答
  •  情深已故
    2021-01-24 01:08

    A bunch of good answers telling you WHAT happens, I thought I'd jump in with WHY.

    There's this thing called the Liskov Substitution Principle, which says that the function in the subclass has to work under the same preconditions and postconditions as the base class. In this case, the function has to be able to operate on any object of type A. Note that because of the inheritance relationships, every B is-a A, but not every A is-a B. So to replace the base method, the new function in the derived class can weaken the preconditions or strengthed the postconditions, but not strengthen preconditions or weaken postconditions.

    Your attempt to override strengthens the precondition, it accepts Bs, not all As.

    Note that covariance IS allowed on return types. If your base class returned A, then it guarantees that the return value is-a A. The base class could then return a B, because every B is-a A.

    But for input parameters, only contravariance meets the theoretical requirements of the LSP, and in/out parameters are invariants. In C++ in particular, all parameter types are invariant for the purposes of overloading.

提交回复
热议问题