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.
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.
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"); }
Point
.x
and y
. The variables and methods below the private
keyword are considered the private members of the class.sum
, as a protected member. Point
class.x
and y
(properties of the class).getX
, getY
, and getSum
. These member functions can be called using the Point
class.Point
class using the new
keyword. getX
method. This method returns the x
value of the current object.getY
method. This method returns the y
value of the current object.getSum
method. This method returns the sum of x
and y
of the current object.RELATED TAGS
CONTRIBUTOR
View all Courses