Structures from the Heap

Structures are also frequently created with new. For instance:

aTapeElement *TapeElement = new aTapeElement;

This reads, “define a pointer to aTapeElement called TapeElement and initialize it with the location of the space created on the heap by new, with that space being the size of aTapeElement.”

You can use the period to select the member variables, but you must dereference the pointer first:

(*TapeElement).Operator = '+';
(*TapeElement).Operand = 234;

Because this is so frequently needed, C++ offers a shorthand for this expression, the pointer member selection (->) operator.

TapeElement->Operator = '+';
TapeElement->Operand = 234;

Naturally, you must always remember to delete a heap-allocated structure, but ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.