Anonymous objects in C++

There are not many cases in which you can have an anonymous *anything* in your code, yet there’s an idiom in C++ which lets you use an object with an anonymous type. Like this:

void foo()
{
   struct {
      int x;
   };
}

Why would this be useful, you may ask. That’s a valid question. This idiom can be very useful to write callbacks, like this:

struct Interface {
   void callback() = 0;
};

void bar(Interface &c);

void foo()
{
   struct : public Interface {
      /* ... */
   } x;

   bar(x);
}

I am not aware of many other uses for an anonymous type. Even more considering this idiom can now be replaced with a much cleaner lambda. But hey, it looks cool!

Advertisements


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s