How do you declare an interface in C++?

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

    My answer is basically the same as the others but I think there are two other important things to do:

    1. Declare a virtual destructor in your interface or make a protected non-virtual one to avoid undefined behaviours if someone tries to delete an object of type IDemo.

    2. Use virtual inheritance to avoid problems whith multiple inheritance. (There is more often multiple inheritance when we use interfaces.)

    And like other answers:

    • Make a class with pure virtual methods.
    • Use the interface by creating another class that overrides those virtual methods.

      class IDemo
      {
          public:
              virtual void OverrideMe() = 0;
              virtual ~IDemo() {}
      }
      

      Or

      class IDemo
      {
          public:
              virtual void OverrideMe() = 0;
          protected:
              ~IDemo() {}
      }
      

      And

      class Child : virtual public IDemo
      {
          public:
              virtual void OverrideMe()
              {
                  //do stuff
              }
      }
      

提交回复
热议问题