O'Reilly logo

Practical C++ Programming, 2nd Edition by Steve Oualline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12. Advanced Types

Total grandeur of a total edifice, Chosen by an inquisitor of structures.

Wallace Stevens

C++ provides a rich set of data types. Through the use of structures, unions, enumerations, and class types, the programmer can extend the language with new types.

Structures

Suppose you are writing an inventory program for a warehouse. The warehouse is filled with bins, each containing a bunch of parts. All the parts in a bin are identical, so you don't have to worry about mixed bins or partials.

For each bin you need to know:

  • The name of the part it holds (30-character string).

  • The quantity on hand (integer).

  • The price (integer cents).

In previous chapters you have used arrays for storing a group of similar data types, but in this example you have a mixed bag: two integers and a string.

Instead of an array, you will use a new data type called a structure. In an array, all the elements are of the same type and are numbered. In a structure, each element, or member, is named and has its own data type.

The general form of a structure definition is:

struct structure-name { 
    member-type 
               member-name;  // Comment 
               member-type 
               member-name;  // Comment 
    . . . . 
} variable-name;

For example, say you want to define a bin to hold printer cables. The structure definition is:

struct bin { 
    char    name[30];   // Name of the part
    int     quantity;   // How many are in the bin
    int     cost;       // The cost of a single part (in cents)
} printer_cable_box;    // Where we put the print cables

This definition actually tells ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required