What is this crazy C++11 syntax ==> struct : bar {} foo {};?

C++C++11

C++ Problem Overview


What could this possibly mean in C++11?

struct : bar {} foo {};

C++ Solutions


Solution 1 - C++

First, we'll take a bog-standard abstract UDT (User-Defined Type):

struct foo { virtual void f() = 0; }; // normal abstract type
foo obj;
// error: cannot declare variable 'obj' to be of abstract type 'foo'

Let's also recall that we can instantiate the UDT at the same time that we define it:

struct foo { foo() { cout << "!"; } };          // just a definition

struct foo { foo() { cout << "!"; } } instance; // so much more
// Output: "!"

Let's combine the examples, and recall that we can define a UDT that has no name:

struct { virtual void f() = 0; } instance; // unnamed abstract type
// error: cannot declare variable 'instance' to be of abstract type '<anonymous struct>'

We don't need the proof about the anonymous UDT any more, so we can lose the pure virtual function. Also renaming instance to foo, we're left with:

struct {} foo;

Getting close.


Now, what if this anonymous UDT were to derive from some base?

struct bar {};       // base UDT
struct : bar {} foo; // anonymous derived UDT, and instance thereof

Finally, C++11 introduces extended initialisers, such that we can do confusing things like this:

int x{0};

And this:

int x{};

And, finally, this:

struct : bar {} foo {};

This is an unnamed struct deriving from bar, instantiated as foo with a blank initializer.

Solution 2 - C++

This defines:

  • an anonymous struct,
  • which is derived publicly from bar
  • which (anonymously) defines nothing else but what it derived from bar
  • and finally, an instance, called "foo" is created,
  • with an empty initializer list

struct : bar {} foo {};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLightness Races in OrbitView Question on Stackoverflow
Solution 1 - C++Lightness Races in OrbitView Answer on Stackoverflow
Solution 2 - C++FrunsiView Answer on Stackoverflow