C++11 interface pure virtual destructor

前端 未结 3 1712
攒了一身酷
攒了一身酷 2021-02-09 03:37

UPD. There is a mark that it is a duplicate of this question. But in that question OP asks HOW to use default to define pure virtual destructor. Th

3条回答
  •  清酒与你
    2021-02-09 04:16

    Variant 1 will allow you to have an instance of the class. Variant 2.1, 2.2 won't allow instances, but allows instances of descendants. This, for example works (and is able to confuse many people), while removing the marked line will make compile fail:

    class I21 {
    public:
        virtual ~I21() = 0;
    };
    
    I21::~I21() {} // remove this and it'll not compile
    
    class I22 : public I21
    {
    public:
        virtual ~I22() {}
    };
    
    int main() {
        I22 i;
        return 0;
    }
    

    The reason behind, the destructor chain calls I21::~I21() directly and not via interface. That said, it's not clear what your goal is with pure virtual destructors. If you'd like to avoid instantiation (i.e., static class), you might consider deleting the constructor instead; if you'd like descendants that can be instantiated but not this class, perhaps you need a pure virtual member function that's implemented in descendants.

提交回复
热议问题