When do I need anonymous class in C++?

eonil picture eonil · Apr 9, 2012 · Viewed 12.6k times · Source

There's a feature called anonymous class in C++. It's similar with anonymous struct in C. I think this feature is invented because of some needs, but I can't figure out what that is.

Can I have some example which really needs anonymous class?

Answer

Mike Seymour picture Mike Seymour · Apr 9, 2012

The feature is there because struct and class are the same thing - anything you can do with one, you can do with the other. It serves exactly the same purpose as an anonymous struct in C; when you want to group some stuff together and declare one or more instances of it, but don't need to refer to that type by name.

It's less commonly used in C++, partly because C++ designs tend to be more type-oriented, and partly because you can't declare constructors or destructors for anonymous classes.