...

/

Nested Functions, Structs, and Classes

Nested Functions, Structs, and Classes

Understand what nested functions, structs and classes are.

Nested functions

Up to this point, we have been defining functions, structs, and classes in the outermost scopes (i.e., the module scope). They can be defined in inner scopes as well. Defining them in inner scopes helps with encapsulation by narrowing the visibility of their symbols, and creating closures, which we covered in the function pointers, delegates, and lambdas chapter.

As an example, the following outerFunc() function contains definitions of a nested function, a nested struct, and a nested class:

Press + to interact
void outerFunc(int parameter) {
int local;
void nestedFunc() {
local = parameter * 2;
}
struct NestedStruct {
void memberFunc() {
local /= parameter;
}
}
class NestedClass {
void memberFunc() {
local += parameter;
}
}
// Using the nested definitions inside this scope:
nestedFunc();
auto s = NestedStruct();
s.memberFunc();
auto c = new NestedClass();
c.memberFunc();
}
void main() {
outerFunc(42);
}

Like any other variable, nested definitions can access symbols that are defined in their outer scopes. For example, all three of the nested ...