|
A structured value is a group of variables that are stored consecutively in memory and that are treated as a single value of a structure type. Define a structure type as in the following example.
struct Elephant { int size; const char* name; };Variables size and name are called fields of type Elephant, and a structure type can have any number of fields.
If e has type Elephant then the fields of e are e.size and e.name.
If p has type Elephant* then the fields of the structure that p points to are p->size and p->name.
Adding constructors to your structures makes it easier to build initialized structured values. Here is a definition of Elephant with a constructor.
struct Elephant { int size; const char* name; Elephant(int s, const char* n) { size = s; name = n; } Elephant() { size = 0; name = NULL; } };Now statement
Elephant jumbo = new Elephant(1000, "Jumbo");creates an Elephant with size 1000 and name "Jumbo". When you use a parameterless constructor, do not write ( ). For example,
Elephant jumbo = new Elephant;initializes the new Elephant using the parameterless constructor.
|