vrijdag 15 juni 2007

Using new to create dynamic structures

Using new with structures has two parts: creating the structure and accessing its members.

inflatable * ps = new inflatable;

This assigns to ps the address of a chunk of free memory large enough to hold a structure of the inflatable type. Note that the syntax is exactly the same as for C++'s build in types.

The tricky part is accessing members. When you create a dynamic structure, you can't use the dot membership operator with the structure name because the structure has NO NAME. All you have is its address. C++ provides an operator just for this situation: the arrow membership operator (->). This operator does for pointer to structures what the dot operator does for structure names.
For example: if ps points to a type inflatable structure, then ps->price is the price member of the pointed-to structure.

REMEMBER
Somethimes new C++ users become confused about when to use the dot operator and when to use the arrow operator to specify a structure member. The rule is simple: If the structure identifier is the name of a structure, use the dot operator. If the identifier is a pointer to the structure, use the arrow operator.

A second, uglier approach to accessing structure members is to realize that if ps is a pointer to a structure, then *ps represents the pointed-to value---the structure itself. Then because *ps is a structure (*ps).price is the price member of the structure. C++'s operator precedence rules require that you use parentheses in this construction.

Geen opmerkingen: