Nesting Functions in C++

Index

If you are a C++ developer who has never learned or used Pascal, the usefulness of this tip may be lost to you. Hopefully you won't neglect the benefits that this tip can bring you, namely better organized code and a resulting ease of maintenance.

In Pascal, you can take portions of a Function or Procedure and break them out, like so:

function sample( parm1: Cardinal, parm2: Cardinal ): Cardinal; var _local_1: Cardinal; function nested( parm1: Cardinal , parm2: Cardinal ): Cardinal; begin if ( parm1 = 0 ) Then Result := parm2; else Result:= nested( parm1 - 1 , parm2 * 2 ); end; begin Result := 0; for _local_1 := 0 to parm2 do Result := Result + nested( _local_1 , parm1 ); end; end;

However, C++ has no direct means of creating nested functions. ...unless you take advantage of one of the more subtle aspects of C++. In C++, you can create local classes, and like all classes, local classes can have static member functions, which means of course, that you can call these member functions. To illustrate, here is the previous example translated to C++.

unsigned int sample( unsigned int parm1 , unsigned int parm2 ) { class _local { public: static unsigned int nested( unsigned int parm1 , unsigned int parm2 ) { if ( parm1 == 0 ) return parm2; else return nested( parm1 - 1 , parm2 * 2 ); } }; unsigned int _result = 0; for( unsigned int _local_1 = 0 ; _local_1 <= parm2 ; ++_local_1 ) _result += _local::nested( _local_1 , parm1 ); return _result; }

If you notice, there is a call to _local::nested( ) after the definition of the local class _local. This looks an awful lot like the Pascal call to nested, doesn't it? It also organizes the source code for sample. Of course, you would use this technique more for routines with more complex flow.

Nested Classes FAQs