Constructors is an actively used design pattern. In class-based object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

?Years Old

Languages with Constructors include action, cfml, cpp, csharp, java, javascript, matlab, object-pascal, objective-c, php, python, visual-basic-dot-net

Example from cfml:

component {
   // properties
   property name="cheeseName";
 
   // constructor
   function Cheese init( required string cheeseName ) {
      variables.cheeseName = arguments.cheeseName;
      return this;
   }
}

Example from cpp:

class Foobar {
 public:
  Foobar(double r = 1.0,
         double alpha = 0.0)  // Constructor, parameters with default values.
      : x_(r * cos(alpha))    // <- Initializer list
  {
    y_ = r * sin(alpha);  // <- Normal assignment
  }

 private:
  double x_;
  double y_;
};
Foobar a,
       b(3),
       c(5, M_PI/4);

Example from csharp:

public class MyClass
{
    private int a;
    private string b;

    // Constructor
    public MyClass() : this(42, "string")
    {
    }

    // Overloading a constructor
    public MyClass(int a, string b)
    {
        this.a = a;
        this.b = b;
    }
}
// Code somewhere
// Instantiating an object with the constructor above
MyClass c = new MyClass(42, "string");

Example from javascript:

class Person {
 constructor(name) {
   this._name = name
 }
}
new Person("Jane")

Last updated February 18th, 2020

Edit Constructors on GitHub