In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special block of statements called when an object is created, either when it is declared (statically constructed on the stack, possible in C++ but not in Java and other object-oriented languages) or dynamically constructed on the heap through the keyword “new”.
A constructor is similar to an instance method, but it differs from a method in that it never has an explicit return type, it's not inherited, and usually has different rules for scope modifiers. Constructors are often distinguished by having the same name as the declaring class. Their responsibility is to initialize the object's data members and to establish the invariant of the class, failing if the invariant isn't valid. A properly written constructor will leave the object in a 'valid' state. Immutable objects must be initialized in a constructor.
The term constructor is also used to denote one of the tags that wraps data in an algebraic data type. This is a different usage than in this article. For more information, see algebraic data type.
In most languages, the constructor can be overloaded in that there can be more than one constructor for a class, each having different parameters. Some languages take consideration of some special types of constructors:
- default constructor - a constructor that can take no arguments
- copy constructor - a constructor that takes one argument of the type of the class (or a reference thereof)
public class myClass
{
private int mA;
private string mB;
public myClass(int a, string b)
{
mA = a;
mB = b;
//code somewhere
//instantiating an object with the constructor above
myClass c = new myClass(42, "string");
}
}
This for C only for the other programming visit http://en.wikipedia.org/wiki/Constructor_(computer_science)
0 comments:
Post a Comment