Home > Enterprise >  Is there any difference between empty derived class and using?
Is there any difference between empty derived class and using?

Time:07-23

I'm writing a library whose functionalities are provided in a C-compatible header like the following:

// File: bar.h

typedef struct bar_context_t bar_context_t;

#ifdef __cplusplus
extern "C" {
#endif

  bar_context_t* bar_create();
  void bar_destroy(bar_context_t*);

  int bar_do_stuff(bar_context_t*);

#ifdef __cplusplus
}
#endif

and implemented in C :

// File: bar.cpp

namespace bar {
  class Context {
    private:
      // ...
    public:
      int do_stuff();
  };
}

The problem is how to connect bar::Context to bar_context_t so I can implement the extern C functions.

I can think of two options:

Option A: Using

using bar_context_t = bar::Context;

Option B: Empty Derived Class

struct bar_context_t : public bar::Context {};

Which option is better? Or is there a better third option?

CodePudding user response:

Neither is necessary (and I don't even think your first variant works; using is just C syntax sugar, and does not introduce a type).

You just declare bar_context_t to be a pointer to bar::Context; that's it. In C, you declare it to be a void*, since C has no type safety anyways.¹


¹strictly speaking, C has type safety, between the two types "function pointer" and "not a function pointer".

  • Related