The first time I heard the constructor term in C ++, I encountered it again in C.
When creating a class, because the object's status (data) is not very clear, you need to initialize it. For example, if we want to create an object in the rectangle class or create a rectangle, we must first determine its length and width. If we cannot determine its length and width, then we cannot create a rectangle. So we need to use a function in this rectangular class to construct all objects in this class-constructor. Since this function is used to create a new object, it cannot be stored after the object, so we must declare and define it in the class.
If there is a class named MyClass, its defined constructor framework is as follows:
public class MyClass{ public MyClass() { }}
Here is an example of how to calculate the area of a rectangle:
First, declare a rectangle class:
Class rectangle {public rectangle (int w, int h) // constructor declaration {width = w; high = h;} public int area () {return width * high ;} private int width; private int high ;}
Second, instantiate the class as A to complete initialization.
Program {static void Main (string [] args) {rectangle A = new rectangle (3, 4); // initialization Console is executed when object A is created. writeLine ("the rectangle area is {0}",. area ());}}
Finally, it should be noted that the constructor does not return values, and a class can have multiple constructor. When using a constructor with parameters, you need to write a constructor with null parameters.