How do you declare an interface in C++?

前端 未结 15 2609
借酒劲吻你
借酒劲吻你 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:50

    All good answers above. One extra thing you should keep in mind - you can also have a pure virtual destructor. The only difference is that you still need to implement it.

    Confused?

    
        --- header file ----
        class foo {
        public:
          foo() {;}
          virtual ~foo() = 0;
    
          virtual bool overrideMe() {return false;}
        };
    
        ---- source ----
        foo::~foo()
        {
        }
    
    

    The main reason you'd want to do this is if you want to provide interface methods, as I have, but make overriding them optional.

    To make the class an interface class requires a pure virtual method, but all of your virtual methods have default implementations, so the only method left to make pure virtual is the destructor.

    Reimplementing a destructor in the derived class is no big deal at all - I always reimplement a destructor, virtual or not, in my derived classes.

提交回复
热议问题