How do you declare an interface in C++?

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

    There is no concept of "interface" per se in C++. AFAIK, interfaces were first introduced in Java to work around the lack of multiple inheritance. This concept has turned out to be quite useful, and the same effect can be achieved in C++ by using an abstract base class.

    An abstract base class is a class in which at least one member function (method in Java lingo) is a pure virtual function declared using the following syntax:

    class A
    {
      virtual void foo() = 0;
    };
    

    An abstract base class cannot be instantiated, i. e. you cannot declare an object of class A. You can only derive classes from A, but any derived class that does not provide an implementation of foo() will also be abstract. In order to stop being abstract, a derived class must provide implementations for all pure virtual functions it inherits.

    Note that an abstract base class can be more than an interface, because it can contain data members and member functions that are not pure virtual. An equivalent of an interface would be an abstract base class without any data with only pure virtual functions.

    And, as Mark Ransom pointed out, an abstract base class should provide a virtual destructor, just like any base class, for that matter.

提交回复
热议问题