Chapter 33. Simulating Nested Functions

Difficulty: 5

C++ has nested classes, but not nested functions. When might nested functions be useful, and can they be simulated in C++?

  1. What is a nested class? Why can it be useful?

  2. What is a local class? Why can it be useful?

  3. C++ does not support nested functions. That is, we cannot write something like

    // Example 33-3
    //
    int f( int i )
    {
      int j = i*2;
    
      int g( int k )  // not valid C++
      {
        return j+k;
      }
    
      j += 4;
    
      return g( 3 );
    }
    

    Demonstrate how it is possible to achieve the same effect in standard C++, and show how to generalize the solution.

Solution

Solution

Recap: Nested and Local Classes

C++ provides many useful tools for ...

Get More Exceptional C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.