Force all classes to implement / override a 'pure virtual' method in multi-level inheritance hierarchy

前端 未结 5 907
孤城傲影
孤城傲影 2020-12-01 20:10

In C++ why the pure virtual method mandates its compulsory overriding only to its immediate children (for object creation), but not to

5条回答
  •  遥遥无期
    2020-12-01 21:01

    What you're basically asking for is to require that the most derived class implement the functiom. And my question is: why? About the only time I can imagine this to be relevant is a function like clone() or another(), which returns a new instance of the same type. And that's what you really want to enforce, that the new instance has the same type; even there, where the function is actually implemented is irrelevant. And you can enforce that:

    class Base
    {
        virtual Base* doClone() const = 0;
    public:
        Base* clone() const
        {
            Base* results = doClone();
            assert( typeid(*results) == typeid(*this) );
            return results;
        }
    }
    

    (In practice, I've never found people forgetting to override clone to be a real problem, so I've never bothered with something like the above. It's a generally useful technique, however, anytime you want to enforce post-conditions.)

提交回复
热议问题