Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dlang
class
flask
d
communitycreator

How to create a class in D

Programming Bytes

Overview

A class is a template definition of the methods and properties (data) in D. The methods and properties are accessible to the objects created for the class. The data and functions within a class are called members of the class.

Creating a class

A class can be created using the class keyword followed by its name. The code example below shows how to create a class in D.

Example

import std.stdio;

class Point { 
  // Private properties that can be accessed only inside the class
  private:
    double x;
    double y; 

  // Protected property can be accessed inside the current class and its child classes
  protected:
    int sum;

  public:
    // Constructor
    this(double x, double y) {
      writeln("Constructor: Object is being created"); 
      this.x = x;
      this.y = y;
    }

    // Public methods that can be accessed by the object
    double getX() {
      return this.x;
    }
    double getY() {
      return this.y;
    }
    double getSum() {
      return this.x + this.y;
    }
    // Destructor 
    ~this() { 
         writeln("Destructor: Object is being deleted"); 
      } 
}
  
void main() {
  // Creating a new object
  Point p1 = new Point(10,10);

  writeln("p1.x => ", p1.getX());
  writeln("p1.y => ", p1.getY());
  writeln("p1.sum => ", p1.getSum());
  writeln("End of main function");
} 
Using classes in D

Explanation

  • Line 3: We create a class, Point.
  • Lines 5–7: We declared the private membersThese are the properties and methods that can be accessed only inside the current class. x and y. The variables and methods below the private keyword are considered the private members of the class.
  • Lines 10–11: We declare an integer, sum, as a protected member.
  • Lines 13–34: We declare the public membersThese are the properties and methods that can be accessed from anywhere outside the class, but within a program. for the Point class.
  • Lines 15–19: We declare a constructor that executes when an object is created for the class. The constructor takes two values as arguments and saves them to x and y (properties of the class).
  • Lines 22–31: We create three member functions: getX, getY, and getSum. These member functions can be called using the Point class.
  • Lines 32–34: We declare a destructor that executes when an object goes out of scope or if we delete it.
  • Line 39: We create a new object for the Point class using the new keyword.
  • Line 41: We call the getX method. This method returns the x value of the current object.
  • Line 42: We call the getY method. This method returns the y value of the current object.
  • Line 43: We call the getSum method. This method returns the sum of x and y of the current object.

RELATED TAGS

dlang
class
flask
d
communitycreator
RELATED COURSES

View all Courses

Keep Exploring