Search⌘ K
AI Features

Encapsulation

Explore encapsulation in D programming to restrict access to struct and class members. Understand how it prevents invalid states and maintains consistency by controlling access through defined interfaces, ensuring safer and more maintainable code structures.

We'll cover the following...

Introduction

All of the structs and classes we have defined so far have been accessible from the outside (main() and other functions in the program).

Let’s consider the following struct:

enum Gender { female, male }

struct Student {
    string name;
    Gender gender;
}

The members of that struct are freely accessible to the rest of the program:

D
import std.stdio;
enum Gender { female, male }
struct Student {
string name;
Gender gender;
this (string name,Gender gender) {
this.name = name;
this.gender = gender;
}
}
void main() {
auto student = Student("Tim", Gender.male);
writefln("%s is a %s student.", student.name, student.gender);
}

Such freedom is a convenience in programs. For example, the previous line was useful for producing the following output:

 ...