Differing return type for virtual functions

前端 未结 4 523
余生分开走
余生分开走 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条回答
  •  轮回少年
    2020-12-19 02:08

    The answer is very similar to the one given for "Why can't I assign a vector to a vector?" on Bjarne Stroustrup's FAQ.

    The ability to modify the return type would lead to a hole in the type safety of the language (see the answer from @GManNickG for a specific example) when dealing with polymorphic types.

    There is one fairly common situation when affecting the return type would be ideal: when returning a polymorphic pointer from a virtual method of a base type. For example,

    class Base {
    public:
        virtual Base* parent() = 0;
    };
    
    class Child : public Base {
    public:
        Base* parent() override
        {
            return parent_;
        }
    private:
        Parent* parent_;  // Assume `Parent` type exists.
    };
    

    Here we lost the type information that Child knows about it's parent_ member. This leads to lots of casting, even though the type was at one point well defined. We can solve this using the Curiously Recurring Template Parameter (CRTP) idiom,

    template
    class Base {
    public:
        virtual ParentType* parent()
        {
            return parent_;
        }
    
    private:
        ParentType* parent_;
    
    };
    
    class Child : public Base {
    };
    

提交回复
热议问题