Protection Attributes

Learn how to specify and define protection attributes.

We'll cover the following

Specifying protection attribute

Protection attributes limit access to the members of structs, classes, and modules. There are two ways to specify protection attributes:

  • At struct or class level to specify the protection of every struct or class member individually

  • At module level to specify the protection of every feature of a module individually: class, struct, function, enum, etc.

Protection attributes can be specified using the following keywords. The default attribute is public.

  • public specifies accessibility by any part of the program without any restriction. An example of this is stdout. Merely importing std.stdio makes stdout available to every module that imports it.

  • private specifies restricted accessibility. Private class members and module members can only be accessed by the module that defines that member. Additionally, private member functions cannot be overridden by subclasses.

  • package specifies package-level accessibility. A feature that is marked as package can be accessed by all of the code that is a part of the same package. The package attribute involves only the innermost package. For example, a package definition that is inside the animal.vertebrate.cat module can be accessed by any other module of the vertebrate package. Similar to the private attribute, package member functions cannot be overridden by subclasses.

  • protected specifies accessibility by derived classes. This attribute extends the private attribute; a protected member can be accessed not only by the module that defines it, but also by the classes that inherit from the class that defines that protected member.

Additionally, the export attribute specifies accessibility from the outside of the program.

Definition

Protection attributes can be specified in three ways.

When written in front of a single definition, it specifies the protection attribute of that definition only. This is similar to the Java programming language:

private int foo;

private void bar() {
    // ...
}

When specified by a colon, it specifies the protection attributes of all of the following definitions until the next specification of a protection attribute. This is similar to the C++ programming language:

private: 
    // ...
    // ...  all of the definitions here are private ...
    // ...
protected: 
    // ... 
    // ...  all of the definitions here are protected ...
    // ...

When specified for a block, the protection attribute is for all of the definitions that are inside that block:

private { 
    // ...
    // ... all of the definitions here are private ...
    // ...
}

Get hands-on with 1400+ tech skills courses.