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

前端 未结 5 964
孤城傲影
孤城傲影 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 20:41

    A pure virtual means that to be instantiated, the pure virtual must be overridden in some descendant of the class that declares the pure virtual function. That can be in the class being instantiated or any intermediate class between the base that declares the pure virtual, and the one being instantiated.

    It's still possible, however, to have intermediate classes that derive from one with a pure virtual without overriding that pure virtual. Like the class that declares the pure virtual, those classes can only be used as based classes; you can't create instances of those classes, only of classes that derive from them, in which every pure virtual has been implemented.

    As far as requiring that a descendant override a virtual, even if an intermediate class has already done so, the answer is no, C++ doesn't provide anything that's at least intended to do that. It almost seems like you might be able to hack something together using multiple (probably virtual) inheritance so the implementation in the intermediate class would be present but attempting to use it would be ambiguous, but I haven't thought that through enough to be sure how (or if) it would work -- and even if it did, it would only do its trick when trying to call the function in question, not just instantiate an object.

提交回复
热议问题