D Programming – Classes & Objects

D Programming – Classes & Objects ”; Previous Next Classes are the central feature of D programming that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class. D Class Definitions When you define a class, you define a blueprint for a data type. This does not actually define any data, but it defines what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object. A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows − class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box } The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section. Defining D Objects A class provides the blueprints for objects, so basically an object is created from a class. You declare objects of a class with exactly the same sort of declaration that you declare variables of basic types. The following statements declare two objects of class Box − Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Both of the objects Box1 and Box2 have their own copy of data members. Accessing the Data Members The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear − Live Demo import std.stdio; class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box } void main() { Box box1 = new Box(); // Declare Box1 of type Box Box box2 = new Box(); // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification box1.height = 5.0; box1.length = 6.0; box1.breadth = 7.0; // box 2 specification box2.height = 10.0; box2.length = 12.0; box2.breadth = 13.0; // volume of box 1 volume = box1.height * box1.length * box1.breadth; writeln(“Volume of Box1 : “,volume); // volume of box 2 volume = box2.height * box2.length * box2.breadth; writeln(“Volume of Box2 : “, volume); } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 It is important to note that private and protected members can not be accessed directly using direct member access operator (.). Shortly you will learn how private and protected members can be accessed. Classes and Objects in D So far, you have got very basic idea about D Classes and Objects. There are further interesting concepts related to D Classes and Objects which we will discuss in various sub-sections listed below − Sr.No. Concept & Description 1 Class member functions A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. 2 Class access modifiers A class member can be defined as public, private or protected. By default members would be assumed as private. 3 Constructor & destructor A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted. 4 The this pointer in D Every object has a special pointer this which points to the object itself. 5 Pointer to D classes A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it. 6 Static members of a class Both data members and function members of a class can be declared as static. Print Page Previous Next Advertisements ”;

D Programming – Interfaces

D Programming – Interfaces ”; Previous Next An interface is a way of forcing the classes that inherit from it to have to implement certain functions or variables. Functions must not be implemented in an interface because they are always implemented in the classes that inherit from the interface. An interface is created using the interface keyword instead of the class keyword even though the two are similar in a lot of ways. When you want to inherit from an interface and the class already inherits from another class then you need to separate the name of the class and the name of the interface with a comma. Let us look at an simple example that explains the use of an interface. Example Live Demo import std.stdio; // Base class interface Shape { public: void setWidth(int w); void setHeight(int h); } // Derived class class Rectangle: Shape { int width; int height; public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getArea() { return (width * height); } } void main() { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. writeln(“Total area: “, Rect.getArea()); } When the above code is compiled and executed, it produces the following result − Total area: 35 Interface with Final and Static Functions in D An interface can have final and static method for which definitions should be included in interface itself. These functions cannot be overriden by the derived class. A simple example is shown below. Example Live Demo import std.stdio; // Base class interface Shape { public: void setWidth(int w); void setHeight(int h); static void myfunction1() { writeln(“This is a static method”); } final void myfunction2() { writeln(“This is a final method”); } } // Derived class class Rectangle: Shape { int width; int height; public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getArea() { return (width * height); } } void main() { Rectangle rect = new Rectangle(); rect.setWidth(5); rect.setHeight(7); // Print the area of the object. writeln(“Total area: “, rect.getArea()); rect.myfunction1(); rect.myfunction2(); } When the above code is compiled and executed, it produces the following result − Total area: 35 This is a static method This is a final method Print Page Previous Next Advertisements ”;

D Programming – Decisions

D Programming – Decisions ”; Previous Next The decision making structures contain condition to be evaluated along with the two sets of statements to be executed. One set of statements is executed if the condition it true and another set of statements is executed if the condition is false. The following is the general form of a typical decision making structure found in most of the programming languages − D programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. D programming language provides the following types of decision making statements. Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 nested switch statements You can use one switch statement inside another switch statement(s). The ? : Operator in D We have covered conditional operator ? : in previous chapter which can be used to replace if…else statements. It has the following general form Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined as follows − Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Print Page Previous Next Advertisements ”;

D Programming – Templates

D Programming – Templates ”; Previous Next Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. Templates are the feature that allows describing the code as a pattern, for the compiler to generate program code automatically. Parts of the source code may be left to the compiler to be filled in until that part is actually used in the program. The compiler fills in the missing parts. Function Template Defining a function as a template is leaving one or more of the types that it uses as unspecified, to be deduced later by the compiler. The types that are being left unspecified are defined within the template parameter list, which comes between the name of the function and the function parameter list. For that reason, function templates have two parameter lists − template parameter list function parameter list Live Demo import std.stdio; void print(T)(T value) { writefln(“%s”, value); } void main() { print(42); print(1.2); print(“test”); } If we compile and run above code, this would produce the following result − 42 1.2 test Function Template with Multiple Type Parameters There can be multiple parameter types. They are shown in the following example. Live Demo import std.stdio; void print(T1, T2)(T1 value1, T2 value2) { writefln(” %s %s”, value1, value2); } void main() { print(42, “Test”); print(1.2, 33); } If we compile and run above code, this would produce the following result − 42 Test 1.2 33 Class Templates Just as we can define function templates, we can also define class templates. The following example defines class Stack and implements generic methods to push and pop the elements from the stack. Live Demo import std.stdio; import std.string; class Stack(T) { private: T[] elements; public: void push(T element) { elements ~= element; } void pop() { –elements.length; } T top() const @property { return elements[$ – 1]; } size_t length() const @property { return elements.length; } } void main() { auto stack = new Stack!string; stack.push(“Test1”); stack.push(“Test2″); writeln(stack.top); writeln(stack.length); stack.pop; writeln(stack.top); writeln(stack.length); } When the above code is compiled and executed, it produces the following result − Test2 2 Test1 1 Print Page Previous Next Advertisements ”;

D Programming – Data Types

D Programming – Data Types ”; Previous Next In the D programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the stored bit pattern is interpreted. The types in D can be classified as follows − Sr.No. Types & Description 1 Basic Types They are arithmetic types and consist of the three types: (a) integer, (b) floating-point, and (c) character. 2 Enumerated types They are again arithmetic types. They are used to define variables that can only be assigned certain discrete integer values throughout the program. 3 The type void The type specifier void indicates that no value is available. 4 Derived types They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types, and (e) Function types. The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function”s return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters. Integer Types The following table gives lists standard integer types with their storage sizes and value ranges − Type Storage size Value range bool 1 byte false or true byte 1 byte -128 to 127 ubyte 1 byte 0 to 255 int 4 bytes -2,147,483,648 to 2,147,483,647 uint 4 bytes 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 ushort 2 bytes 0 to 65,535 long 8 bytes -9223372036854775808 to 9223372036854775807 ulong 8 bytes 0 to 18446744073709551615 To get the exact size of a type or a variable, you can use the sizeof operator. The expression type.(sizeof) yields the storage size of the object or type in bytes. The following example gets the size of int type on any machine − Live Demo import std.stdio; int main() { writeln(“Length in bytes: “, ulong.sizeof); return 0; } When you compile and execute the above program, it produces the following result − Length in bytes: 8 Floating-Point Types The following table mentions standard float-point types with storage sizes, value ranges, and their purpose − Type Storage size Value range Purpose float 4 bytes 1.17549e-38 to 3.40282e+38 6 decimal places double 8 bytes 2.22507e-308 to 1.79769e+308 15 decimal places real 10 bytes 3.3621e-4932 to 1.18973e+4932 either the largest floating point type that the hardware supports, or double; whichever is larger ifloat 4 bytes 1.17549e-38i to 3.40282e+38i imaginary value type of float idouble 8 bytes 2.22507e-308i to 1.79769e+308i imaginary value type of double ireal 10 bytes 3.3621e-4932 to 1.18973e+4932 imaginary value type of real cfloat 8 bytes 1.17549e-38+1.17549e-38i to 3.40282e+38+3.40282e+38i complex number type made of two floats cdouble 16 bytes 2.22507e-308+2.22507e-308i to 1.79769e+308+1.79769e+308i complex number type made of two doubles creal 20 bytes 3.3621e-4932+3.3621e-4932i to 1.18973e+4932+1.18973e+4932i complex number type made of two reals The following example prints storage space taken by a float type and its range values − Live Demo import std.stdio; int main() { writeln(“Length in bytes: “, float.sizeof); return 0; } When you compile and execute the above program, it produces the following result on Linux − Length in bytes: 4 Character Types The following table lists standard character types with storage sizes and its purpose. Type Storage size Purpose char 1 byte UTF-8 code unit wchar 2 bytes UTF-16 code unit dchar 4 bytes UTF-32 code unit and Unicode code point The following example prints storage space taken by a char type. Live Demo import std.stdio; int main() { writeln(“Length in bytes: “, char.sizeof); return 0; } When you compile and execute the above program, it produces the following result − Length in bytes: 1 The void Type The void type specifies that no value is available. It is used in two kinds of situations − Sr.No. Types & Description 1 Function returns as void There are various functions in D which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); 2 Function arguments as void There are various functions in D which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void); The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters. Print Page Previous Next Advertisements ”;

D Programming – Quick Guide

D Programming – Quick Guide ”; Previous Next D Programming – Overview D programming language is an object-oriented multi-paradigm system programming language developed by Walter Bright of Digital Mars. Its development started in 1999 and was first released in 2001. The major version of D(1.0) was released in 2007. Currently, we have D2 version of D. D is language with syntax being C style and uses static typing. There are many features of C and C++ in D but also there are some features from these language not included part of D. Some of the notable additions to D includes, Unit testing True modules Garbage collection First class arrays Free and open Associative arrays Dynamic arrays Inner classes Closures Anonymous functions Lazy evaluation Closures Multiple Paradigms D is a multiple paradigm programming language. The multiple paradigms includes, Imperative Object Oriented Meta programming Functional Concurrent Example Live Demo import std.stdio; void main(string[] args) { writeln(“Hello World!”); } Learning D The most important thing to do when learning D is to focus on concepts and not get lost in language technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. Scope of D D programming has some interesting features and the official D programming site claims that D is convinient, powerful and efficient. D programming adds many features in the core language which C language has provided in the form of Standard libraries such as resizable array and string function. D makes an excellent second language for intermediate to advanced programmers. D is better in handling memory and managing the pointers that often causes trouble in C++. D programming is intended mainly on new programs that conversion of existing programs. It provides built in testing and verification an ideal for large new project that will be written with millions of lines of code by large teams. D Programming – Environment Local Environment Setup for D If you are still willing to set up your environment for D programming language, you need the following two softwares available on your computer, (a) Text Editor,(b)D Compiler. Text Editor for D Programming This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for D programs are named with the extension “.d“. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it and finally execute it. The D Compiler Most current D implementations compile directly into machine code for efficient execution. We have multiple D compilers available and it includes the following. DMD − The Digital Mars D compiler is the official D compiler by Walter Bright. GDC − A front-end for the GCC back-end, built using the open DMD compiler source code. LDC − A compiler based on the DMD front-end that uses LLVM as its compiler back-end. The above different compilers can be downloaded from D downloads We will be using D version 2 and we recommend not to download D1. Lets have a helloWorld.d program as follows. We will use this as first program we run on platform you choose. Live Demo import std.stdio; void main(string[] args) { writeln(“Hello World!”); } We can see the following output. $ hello world Installation of D on Windows Download the windows installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − C:DProgramming> DMD helloWorld.d C:DProgramming> helloWorld We can see the following output. hello world C:DProgramming is the folder, I am using to save my samples. You can change it to the folder that you have saved D programs. Installation of D on Ubuntu/Debian Download the debian installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world Installation of D on Mac OS X Download the Mac installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world Installation of D on Fedora Download the fedora installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world Installation of D on OpenSUSE Download the OpenSUSE installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world D IDE We have

D Programming – Discussion

Discuss D Programming ”; Previous Next D programming language is an object-oriented multi-paradigm system programming language. D programming is actually developed by re-engineering C++ programming language, but it is distinct programming language that not only takes in some features of C++ but also some features of other programming languages such as Java, C#, Python, and Ruby. This tutorial covers various topics ranging from the basics of the D programming language to advanced OOP concepts along with the supplementary examples. Print Page Previous Next Advertisements ”;

D Programming – Encapsulation

D Programming – Encapsulation ”; Previous Next All D programs are composed of the following two fundamental elements − Program statements (code) − This is the part of a program that performs actions and they are called functions. Program data − It is the information of the program which affected by the program functions. Encapsulation is an Object Oriented Programming concept that binds data and functions that manipulate the data together, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. D supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected, and public members. By default, all items defined in a class are private. For example − class Box { public: double getVolume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved. To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program. Making one class a friend of another exposes the implementation details and reduces encapsulation. It is ideal to keep as many details of each class hidden from all other classes as possible. Data Encapsulation in D Any D program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example − Example Live Demo import std.stdio; class Adder { public: // constructor this(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; } void main( ) { Adder a = new Adder(); a.addNum(10); a.addNum(20); a.addNum(30); writeln(“Total “,a.getTotal()); } When the above code is compiled and executed, it produces the following result − Total 60 Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly. Class Designing Strategy in D Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That is just good encapsulation. This wisdom is applied most frequently to data members, but it applies equally to all members, including virtual functions. Print Page Previous Next Advertisements ”;

D Programming – Abstract Classes

D Programming – Abstract Classes ”; Previous Next Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class. If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own. Using Abstract Class in D Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword. The following shows an example of how abstract class can be inherited and used. Example Live Demo import std.stdio; import std.string; import std.datetime; abstract class Person { int birthYear, birthDay, birthMonth; string name; int getAge() { SysTime sysTime = Clock.currTime(); return sysTime.year – birthYear; } } class Employee : Person { int empID; } void main() { Employee emp = new Employee(); emp.empID = 101; emp.birthYear = 1980; emp.birthDay = 10; emp.birthMonth = 10; emp.name = “Emp1”; writeln(emp.name); writeln(emp.getAge); } When we compile and run the above program, we will get the following output. Emp1 37 Abstract Functions Similar to functions, classes can also be abstract. The implementation of such function is not given in its class but should be provided in the class that inherits the class with abstract function. The above example is updated with abstract function. Example Live Demo import std.stdio; import std.string; import std.datetime; abstract class Person { int birthYear, birthDay, birthMonth; string name; int getAge() { SysTime sysTime = Clock.currTime(); return sysTime.year – birthYear; } abstract void print(); } class Employee : Person { int empID; override void print() { writeln(“The employee details are as follows:”); writeln(“Emp ID: “, this.empID); writeln(“Emp Name: “, this.name); writeln(“Age: “,this.getAge); } } void main() { Employee emp = new Employee(); emp.empID = 101; emp.birthYear = 1980; emp.birthDay = 10; emp.birthMonth = 10; emp.name = “Emp1″; emp.print(); } When we compile and run the above program, we will get the following output. The employee details are as follows: Emp ID: 101 Emp Name: Emp1 Age: 37 Print Page Previous Next Advertisements ”;

D Programming – Structs

D Programming – Structs ”; Previous Next The structure is yet another user defined data type available in D programming, which allows you to combine data items of different kinds. Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID Defining a Structure To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this − struct [structure tag] { member definition; member definition; … member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure”s definition before the semicolon, you can specify one or more structure variables which are optional. Here is the way you would declare the Books structure − struct Books { char [] title; char [] author; char [] subject; int book_id; }; Accessing Structure Members To access any member of a structure, you use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. The following example explains the usage of structure − Live Demo import std.stdio; struct Books { char [] title; char [] author; char [] subject; int book_id; }; void main( ) { Books Book1; /* Declare Book1 of type Book */ Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = “D Programming”.dup; Book1.author = “Raj”.dup; Book1.subject = “D Programming Tutorial”.dup; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = “D Programming”.dup; Book2.author = “Raj”.dup; Book2.subject = “D Programming Tutorial”.dup; Book2.book_id = 6495700; /* print Book1 info */ writeln( “Book 1 title : “, Book1.title); writeln( “Book 1 author : “, Book1.author); writeln( “Book 1 subject : “, Book1.subject); writeln( “Book 1 book_id : “, Book1.book_id); /* print Book2 info */ writeln( “Book 2 title : “, Book2.title); writeln( “Book 2 author : “, Book2.author); writeln( “Book 2 subject : “, Book2.subject); writeln( “Book 2 book_id : “, Book2.book_id); } When the above code is compiled and executed, it produces the following result − Book 1 title : D Programming Book 1 author : Raj Book 1 subject : D Programming Tutorial Book 1 book_id : 6495407 Book 2 title : D Programming Book 2 author : Raj Book 2 subject : D Programming Tutorial Book 2 book_id : 6495700 Structures as Function Arguments You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example − Live Demo import std.stdio; struct Books { char [] title; char [] author; char [] subject; int book_id; }; void main( ) { Books Book1; /* Declare Book1 of type Book */ Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = “D Programming”.dup; Book1.author = “Raj”.dup; Book1.subject = “D Programming Tutorial”.dup; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = “D Programming”.dup; Book2.author = “Raj”.dup; Book2.subject = “D Programming Tutorial”.dup; Book2.book_id = 6495700; /* print Book1 info */ printBook( Book1 ); /* Print Book2 info */ printBook( Book2 ); } void printBook( Books book ) { writeln( “Book title : “, book.title); writeln( “Book author : “, book.author); writeln( “Book subject : “, book.subject); writeln( “Book book_id : “, book.book_id); } When the above code is compiled and executed, it produces the following result − Book title : D Programming Book author : Raj Book subject : D Programming Tutorial Book book_id : 6495407 Book title : D Programming Book author : Raj Book subject : D Programming Tutorial Book book_id : 6495700 Structs Initialization Structs can be initialized in two forms, one using construtor and other using the {} format. An example is shown below. Example Live Demo import std.stdio; struct Books { char [] title; char [] subject = “Empty”.dup; int book_id = -1; char [] author = “Raj”.dup; }; void main( ) { Books Book1 = Books(“D Programming”.dup, “D Programming Tutorial”.dup, 6495407 ); printBook( Book1 ); Books Book2 = Books(“D Programming”.dup, “D Programming Tutorial”.dup, 6495407,”Raj”.dup ); printBook( Book2 ); Books Book3 = {title:”Obj C programming”.dup, book_id : 1001}; printBook( Book3 ); } void printBook( Books book ) { writeln( “Book title : “, book.title); writeln( “Book author : “, book.author); writeln( “Book subject : “, book.subject); writeln( “Book book_id : “, book.book_id); } When the above code is compiled and executed, it produces the following result − Book title : D Programming Book author : Raj Book subject : D Programming Tutorial Book book_id : 6495407 Book title : D Programming Book author : Raj Book subject : D Programming Tutorial Book book_id : 6495407 Book title : Obj C programming Book author : Raj Book subject : Empty Book book_id : 1001 Static Members Static variables are initialized only once. For example, to have the unique ids for the books we can make the book_id as static and increment the book id. An example is shown below. Example Live Demo import std.stdio; struct Books { char [] title; char [] subject = “Empty”.dup; int book_id; char [] author = “Raj”.dup; static int id = 1000; }; void main( ) { Books Book1 = Books(“D Programming”.dup, “D Programming Tutorial”.dup,++Books.id ); printBook( Book1 ); Books Book2 = Books(“D Programming”.dup, “D Programming Tutorial”.dup,++Books.id); printBook( Book2 ); Books Book3 = {title:”Obj C programming”.dup, book_id:++Books.id}; printBook( Book3 ); } void printBook( Books book ) { writeln( “Book title : “, book.title); writeln( “Book