Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
A constructor is a method that has the same name as its class (and which has no return value). Three constructors are defined in Program . The purpose of a constructor is to initialize an object. A constructor is invoked whenever a new instance of a class is created using the new operator.
Consider the following sequence of variable declarations:
Complex c = new Complex(); // calls Complex () Complex d = new Complex(2.0); // calls Complex (double) Complex i = new Complex(0, 1); // calls Complex (double, double)
Consider the constructor that takes two double arguments, x and y (lines 6-10). This constructor initializes the complex number by assigning x and y to the real and imag fields, respectively.