views:

252

answers:

1

Hi all,

I've just come across the following code:

#include <iostream>

static class Foo
{
public:
    Foo()
    {
        std::cout << "HELLO" << std::endl;
    }

    void foo()
    {
        std::cout << "in foo" << std::endl;
    }

}
    blah;

int main()
{
    std::cout << "exiting" << std::endl;
    blah.foo();
    return 0;
}

I haven't seen the above method of definining a variable before - the class definition is done inline with the variable definition. It reminds me of anonymous classes in Java. What is this called, and is it in the C++ standard?

Thanks

Taras

+1  A: 

It's quite standard to define a class (or struct, perfectly equivalent except that the default is public instead of private) and declare a variable of its type (or pointer to such a variable, etc) -- it was OK in C (with struct, but as I already mentioned C++'s class, save for public vs private, is the same thing as struct) and C++ mostly maintains upwards compatibility with (ISO-1989) C. Never heard it called by any special name.

Alex Martelli
Is it necessary for the class to be named in this case (i.e., are anonymous classes permitted in C++)? And, since it is named, can you still create other `Foo` objects?
... soon to be compatibility with ISO C99. I should add, though, that this usage is quite rare in idiomatic C++, even though it is legal.
Michael Aaron Safyan
@STingRaySC: no, anonymous classes are fine, and yes, you can create others. In fact you can create two even if it is anonymous: `struct { … } foo1, foo2;`.
Potatoswatter
Very cool. I think that's an underused facility in C++.
Also worth pointing out that if the class is unnamed, you may not put that declaration at namespace scope. It has to be local then (the rationale is: You cannot redeclare in another TU anyway - the variables there will have a different type).
Johannes Schaub - litb