|
Constructors are a feature that make initialization of structures convenient. After defining a constructor for type Cell appropriately, you can write one line,
Cell* p = new Cell(22, "fixed");instead of three lines,
Cell* p = new Cell; p->item = 22; p->name = "fixed";
A constructor definition looks like a function definition, with parameters, but it has no return-type. The constructor's name must be the same as the name of the type. Within the constructor definition, initialize the fields. For example,
struct Cell { int item; const char* name; Cell(int it, const char* nm) { item = it; name = nm; } };defines type Cell with two fields and a constructor that takes two parameters.
It is good policy to initialize every field of a structure in a constructor. That does not necessarily mean that the constructor has a parameter for each field, but many constructors do.
You can use a constructor in three ways, which we illustrate for type Cell. For our purposes, the first one is most important.
Cell* p = new Cell(20, "a cell");
Expression new Cell(it,nm) creates a new cell in the heap and runs the constructor on that new cell, with the given parameters. The expression's value is a pointer to the new cell, and new Cell(it, nm) has type Cell*. |
Cell c(20, "a cell");
This is equivalent to
Cell c;
c.item = 20;
c.name = "a cell";
|
Cell(20, "a cell")
Expression
Cell(it, nm) creates a cell
in the frame of the current function and
initializes that cell.
Expression Cell(it, nm) has type Cell.
For example,
Cell c = Cell(20, "a cell");is equivalent to
Cell c(20, "a cell");
|
|