Constructor function
A constructor function, in computer programming, is a member function of a class used to create an object instance of a particular class and possibly also populate some or all of that object instance's attributes. In some languages, particularly those derived from C++, a constructor is a method with the same name as its class; in others, it is a method with a specific reserved name such as "init", "New", or "Constructor".
In languages which support method overloading, a class may have more than one constructor function, thereby allowing multiple ways to create an object instance. In example 2 below, an instance of an account can be created without supplying an initial balance and one where an initial balance can be supplied in the call to the constructor function.
Example 1. (In JavaScript)
// constructor function function MyObject(attributeA, attributeB) { this.attributeA = attributeA this.attributeB = attributeB } // create an Object obj = new MyObject('red', 1000)
Example 2. (In Java)
public class Account { protected double balance; // Constructor function public Account() { balance = 0.0; } // Constructor function to initialize balance public Account( double amount ) { balance = amount; } public double getbalance() { return balance; } } public class AccountTester { public static void main( String args[] ) { // Create an empty account Account acc1 = new Account(); // Create an account with a balance Account acc2 = new Account( 5000.0 ); } }