What does "class :" mean in C++?

C++ClassColon

C++ Problem Overview


I've never seen it before. I thought it was a typo for "::sample", but when I saw it actually compiles I was very confused. Can anyone help me find out please? I don't think it's a goto label.

void f() {
  class: sample {
    // there were some members declared here
  } x;
}

C++ Solutions


Solution 1 - C++

It is an unnamed class, and the colon means it inherits privately from sample. See it like

class Foo : private sample
{
    // ...
};

Foo x;

Solution 2 - C++

I think that is defining an unnamed class deriving from sample. And x is a variable of that unnamed class.

struct sample{ int i;};
 
sample f() 
{
  struct : sample 
  {
    // there were some members declared here
  } x;
  x.i = 10;
  return x;
}
int main() 
{
        sample s = f();
        cout << s.i << endl;
        return 0;
}

Sample code at ideone : http://www.ideone.com/6Mj8x

PS: I changed class to struct for accessibility reason!

Solution 3 - C++

That's an unnamed class.

You can use them e.g. to substitute for local functions in pre-C++11:

int main() {
    struct {
        int operator() (int i) const {                 
            return 42;
        }
    } nice;
    
    nice(0xbeef);
}

The colon followed by sample simply means derive from sample using default inheritance. (for structs: public, for classes: private)

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
QuestionJohannes Schaub - litbView Question on Stackoverflow
Solution 1 - C++Alexandre C.View Answer on Stackoverflow
Solution 2 - C++NawazView Answer on Stackoverflow
Solution 3 - C++Sebastian MachView Answer on Stackoverflow