How do you declare an interface in C++?

前端 未结 15 2563
借酒劲吻你
借酒劲吻你 2020-11-22 03:26

How do I setup a class that represents an interface? Is this just an abstract base class?

15条回答
  •  盖世英雄少女心
    2020-11-22 03:56

    As far I could test, it is very important to add the virtual destructor. I'm using objects created with new and destroyed with delete.

    If you do not add the virtual destructor in the interface, then the destructor of the inherited class is not called.

    class IBase {
    public:
        virtual ~IBase() {}; // destructor, use it to call destructor of the inherit classes
        virtual void Describe() = 0; // pure virtual method
    };
    
    class Tester : public IBase {
    public:
        Tester(std::string name);
        virtual ~Tester();
        virtual void Describe();
    private:
        std::string privatename;
    };
    
    Tester::Tester(std::string name) {
        std::cout << "Tester constructor" << std::endl;
        this->privatename = name;
    }
    
    Tester::~Tester() {
        std::cout << "Tester destructor" << std::endl;
    }
    
    void Tester::Describe() {
        std::cout << "I'm Tester [" << this->privatename << "]" << std::endl;
    }
    
    
    void descriptor(IBase * obj) {
        obj->Describe();
    }
    
    int main(int argc, char** argv) {
    
        std::cout << std::endl << "Tester Testing..." << std::endl;
        Tester * obj1 = new Tester("Declared with Tester");
        descriptor(obj1);
        delete obj1;
    
        std::cout << std::endl << "IBase Testing..." << std::endl;
        IBase * obj2 = new Tester("Declared with IBase");
        descriptor(obj2);
        delete obj2;
    
        // this is a bad usage of the object since it is created with "new" but there are no "delete"
        std::cout << std::endl << "Tester not defined..." << std::endl;
        descriptor(new Tester("Not defined"));
    
    
        return 0;
    }
    

    If you run the previous code without virtual ~IBase() {};, you will see that the destructor Tester::~Tester() is never called.

提交回复
热议问题