Differing return type for virtual functions

前端 未结 4 522
余生分开走
余生分开走 2020-12-19 01:20

A virtual function\'s return type should be the same type that is in base class, or covariant. But why do we have this restriction?

4条回答
  •  -上瘾入骨i
    2020-12-19 01:53

    Because how would the code that's using the return value cope with all sorts of unrelated types coming back? e.g.:

    class A
    {
    public:
        virtual float func();
    };
    
    class B: public A
    {
    public:
        virtual char *func();
    };
    
    A *p = (some_condition) ? new A() : new B();
    p->func();  // Oh no! What is the type?
    

提交回复
热议问题