what is local class and its significance in c++? local class is a class which is declare inside a function.  For example in below example class cLocal is a local class and it becomes local to the function foo.

#include<iostream>
using namespace std;

void foo ()
{
  class cLocal
  {
      int a;
      cLocal () { a = 0; }

  };
}

int main ()
{
  return 0;
}
  • local classes cannot define static member variable and cannot access non static local variables. so when we will compile below sample program it will error out.
#include<iostream>
using namespace std;

void foo ()
{
  class cLocal
  {
      static int a;
      cLocal () { a = 0; }

  };
}

int main ()
{
  return 0;
}
localcl.cpp:8:18: error: local class ‘class foo()::cLocal’ 
shall not have static data member ‘int foo()::cLocal::a’ [-fpermissive]
       static int a;
                  ^

Why local classes are not allowed static data member?

  • local classes can be considered as a final classes because we cannot derive a new class from the local class. however we can derive a new class from local class inside the function in which local class is declared.
#include<iostream>
using namespace std;

void foo ()
{
  class cLocal
  {
      int a;
      cLocal () { a = 0; }

  };

  class mylocal : public cLocal{}; //ok
}

// it will error out
class der:public cLocal
{

};

int main() { return 0; }

what is local class and its significance in c++?

Use case 1.

Let us assume that we have an requirement such that only a particular function can create an object of a class. In this case the class needs to be local to that function. We cannot create new object of a local class outside of function.

#include<iostream>
using namespace std;

void foo()
{
    class local{};
    local *obj = new local;//ok
}

int main() {
   local *l = new local; // error
   return 0;
}

Use case 2:

  • Local classes are used to create trampoline functions.

ref:

https://www.quora.com/What-is-the-use-of-local-classes-in-c++



Related Contents to follow