How to create a class in D
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 classprivate:double x;double y;// Protected property can be accessed inside the current class and its child classesprotected:int sum;public:// Constructorthis(double x, double y) {writeln("Constructor: Object is being created");this.x = x;this.y = y;}// Public methods that can be accessed by the objectdouble 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 objectPoint 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");}
Explanation
- Line 3: We create a class,
Point. - Lines 5–7: We declared the
private members These are the properties and methods that can be accessed only inside the current class. xandy. The variables and methods below theprivatekeyword 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
for thepublic members These are the properties and methods that can be accessed from anywhere outside the class, but within a program. Pointclass. - 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
xandy(properties of the class). - Lines 22–31: We create three member functions:
getX,getY, andgetSum. These member functions can be called using thePointclass. - 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
Pointclass using thenewkeyword. - Line 41: We call the
getXmethod. This method returns thexvalue of the current object. - Line 42: We call the
getYmethod. This method returns theyvalue of the current object. - Line 43: We call the
getSummethod. This method returns the sum ofxandyof the current object.