Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

What could this possibly mean in C++11?

struct : bar {} foo {}; 
like image 906
Lightness Races in Orbit Avatar asked Aug 15 '11 16:08

Lightness Races in Orbit


1 Answers

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.

like image 98
Lightness Races in Orbit Avatar answered Oct 07 '22 01:10

Lightness Races in Orbit