Information Technology Reference
In-Depth Information
Keyword Parentheses are required.
↓
↓
new
TypeName
()
↑
Type
If the memory allocated is for a reference type, the object-creation expression returns a
reference to the allocated and initialized instance of the type in the heap.
This is exactly what you need to allocate and initialize the memory to hold the class
instance data. Use the
new
operator to create an object-creation expression, and assign the
value returned by it to the class variable. Here's an example:
Dealer TheDealer; // Declare variable for the reference.
TheDealer =
new Dealer()
; // Allocate memory for the class object.
↑
Object-creation expression
The code on the left in Figure 4-3 shows the
new
operator used to allocate memory and cre-
ate an instance of class
Dealer
, which is then assigned to the class variable. The memory
structure is illustrated on the right side of the figure.
Figure 4-3.
Allocating memory for the data of a class variable
Combining the Steps
The two steps can be combined by
initializing
the variable with the object-creation expression.
Declare variable
↓
Dealer TheDealer =
new Dealer();
// Declare and initialize.
↑
Initialize with an object-creation expression.