C++: using a base class as the implementation of an interface

前端 未结 5 1093
南方客
南方客 2020-12-14 16:01

In C++ is it possible to use another base class to provide the implementation of an interface (i.e. abstract base class) in a derived class?

class Base
{
          


        
5条回答
  •  悲&欢浪女
    2020-12-14 16:33

    If Base isn't derived from Interface, then you'll have to have forwarding calls in Derived. It's only "overhead" in the sense that you have to write extra code. I suspect the optimizer will make it as efficient as if your original idea had worked.

    class Interface {
        public:
            virtual void myfunction() = 0;
    };
    
    class Base {
        public:
            virtual void myfunction() {/*...*/}
    };
    
    class Derived : public Interface, public Base {
        public:
            void myfunction() { Base::myfunction(); }  // forwarding call
    };
    
    int main() {
       Derived d;
       d.myfunction();
       return 0;
    }
    

提交回复
热议问题