How can I simulate interfaces in C++?

后端 未结 9 2109
时光说笑
时光说笑 2020-12-04 19:22

Since C++ lacks the interface feature of Java and C#, what is the preferred way to simulate interfaces in C++ classes? My guess would be multiple inheritance o

9条回答
  •  粉色の甜心
    2020-12-04 20:11

    If you don't use virtual inheritance, the overhead should be no worse than regular inheritance with at least one virtual function. Each abstract class inheritted from will add a pointer to each object.

    However, if you do something like the Empty Base Class Optimization, you can minimize that:

    struct A
    {
        void func1() = 0;
    };
    
    struct B: A
    {
        void func2() = 0;
    };
    
    struct C: B
    {
        int i;
    };
    

    The size of C will be two words.

提交回复
热议问题