C++ – Passing unnamed classes through functions


How do I pass this instance as a parameter into a function?

    void foo();
} bar;

Do I have to name the class?
It is copyable since I haven't made the class's copy ctor private.
So how is it possible if at all?

Best Solution

Maybe it would be better if you explicit what you want to do. Why do you want to create an unnamed class? Does it conform to an interface? Unnamed classes are quite limited, they cannot be used as parameters to functions, they cannot be used as template type-parameters...

Now if you are implmenting an interface then you can pass references to that interface:

class interface {
   virtual void f() const = 0;
void function( interface const& o )
int main()
   class : public interface {
      virtual void f() const {
         std::cout << "bar" << std::endl;
   } bar;
   function( bar ); // will printout "bar"

NOTE: For all those answers that consider template arguments as an option, unnamed classes cannot be passed as template type arguments.

C++ Standard. 14.3.1, paragraph 2:

2 A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

If you test with comeau compiler (the link is for the online tryout) you will get the following error:

error: a template argument may not reference an unnamed type

As a side note, comeau compiler is the most standard compliant compiler I know of, besides being the one with the most helpful error diagnostics I have tried.

NOTE: Comeau and gcc (g++ 4.0) give an error with the code above. Intel compiler (and from other peoples comments MSVS 2008) accept using unnamed classes as template parameters, against the standard.