Home > Blogs > The C++ Features I Like Most Series: Local Classes

The C++ Features I Like Most Series: Local Classes

By  Dec 28, 2008

Topics: Programming, C/C++

With all due modesty, I believe that the first article to recognize the potential of local classes in C++ was a C++ 10 Minute Solution from 2004 which introduced the "disposable classes" idiom. Prior to that article, local classes were merely a recondite curiosity in the C++98 standard. What's so special about local classes then? Local classes have served C++ twice: in refuting the claim that C++ needed to import finally and later, in the design of C++09 lambdas.

Local Classes And finally
In the early 2000s, there were several proposals for adding finally to C++. finally was never needed in C++ but Java programmers who got used to writing try-catch-finally blocks all over the place were desperately looking for this tedious idiom in C++. I stood against that attempt to import a completely unnecessary -- not to say harmful -- idiom to C++. Fortunately, I was able to prove that the disposable classes idiom, i.e. defining a local class whose destructor performs localized unconditional cleanup operations, made finally completely redundant in C++ (this technique is demonstrated in detail in the aforementioned 10 Minuet Solution). The comments I received after writing that Solution taught me that local classes were indeed hardly known to the average C++ programmers: some readers looked at them with awe, whereas the few who did know local classes sent me reprimanding emails: "local classes can't have static data members!" and "local classes can't have virtual functions or base classes!". Guess what? These "limitations" are exactly the features that make local classes a perfect substratum for implementing the disposable class idiom, and others.

I can't say whether it was my seminal paper that led committee members to reflect on local classes, but I later found out that some of them clearly acknowledged that "implementation can use local classes to implement finally". In other words, committee members realized that compilers, not human programmers, could benefit most from using local classes under the hood. Indeed, this discovery was soon translated into a key C++09 feature called lambda expressions and closures. As you probably know, a lambda expression is a nameless function defined at the place of call. The compiler implicitly translates a lambda expression into a closure, which is a compiler-generated local class that contains the lambda expression inside an overloaded operator(). Indeed, you're not going to use local classes directly in C++09 more often than ever before. However, every time you're using a lambda expression in a C++09-enabled compiler, you'll be using local classes indirectly. Who said local classes were of no use?

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.