D Programming - Classes & Objects-Class access modifiers-Constructor & destructor - D Programming Language

The Class Constructor

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

A constructor has exactly the same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

The following example explains the concept of constructor −

When the above code is compiled and executed, it produces the following result −

Parameterized Constructor

A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps you to assign initial value to an object at the time of its creation as shown in the following example −

Example

When the above code is compiled and executed, it produces the following result −

The Class Destructor

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

A destructor has exactly the same name as the class prefixed with a tilde (~). It can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

The following example explains the concept of destructor −

When the above code is compiled and executed, it produces the following result −

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

D Programming Language Topics