Home > C++, Dev > v-table on the reinterpret_cast

v-table on the reinterpret_cast

In this small writing, I’ll show you a trick to implement multiple copies of an interface by a single class. Let’s consider two interfaces I1 and I2.

struct I1 {
   virtual void foo() = 0;

struct I2 {
   virtual void bar() = 0;

When a pointer of I1 * is cast to I2 * by reinterpret_cast, it’s still safe to call its method from v-table perspective, well, as long as memory layout (though there is none in this example). Thus, this kind of pointer cast can be considered as casting two compatible interface pointers.

It’s not a complex trick and a piece of instantly runnable code is more than many words.

#include <stdio.h>

// Infrastructure {
// IFooX is a meta generator to ensure that interfaces are generated compatible
#define IFooX(id) \
struct IFoo##id {\
    virtual void invoke##id() = 0;\
    IFoo *getIFoo##id() {\
        return reinterpret_cast<IFoo *>(this);\

IFooX(); // define the infrastructure level interface IFoo that can be
         // shared among modules or crossing applications.
// }

// Application {

struct Application : IFoo1, IFoo2 {
    virtual void invoke1() {

    virtual void invoke2() {

int main() {
    Application application;
    return 0;
// }
Categories: C++, Dev
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: