Local Classes
09 Jul 2018
Generally speaking it’s always good advice to keep your variables as local as possible. (Unless you have evidence against it for a particular use case). The same can be said for classes. If you have a class that is either not going to be instantiated outside a particular function / lambda or you want to disallow it’s use elsewhere, make it local to that function or lambda.
auto CreateSymbol(int type, int size)
{
struct Symbol {
int Type;
int Size;
};
return Symbol{type, size};
}
int GetSymbolSpec()
{
// Either auto or a template argument is a must
auto sym = CreateSymbol(6, 8);
// It's members are still accessible
return sym.Type + sym.Size;
}
This can be useful in cases such as creating abstract factories, types that are internal to classes, or even just adding a cheap & hidden abstraction.