The C++ language allows you to create and
use data types other than the fundamental data types. These
types are called user-defined data types. There are two ways
by which a user-defined data type can be created. The first
is by using the keyword struct, and the second is by using
the keyword class. Data types defined using the keyword
struct are called structures.
In C++, a structure is a collection of variables that are
referenced by a single name. The variable can be of
different data types. They provide a convenient means of
keeping related information together. Structure definition
forms a template which is then used to create structure
variables. The variables that make up the structure are
called structure elements.
All the elements found in the structure are related to each
other. For example, the invoice number and the invoice
amount found in an invoice would normally be represented in
a structure. The following code segment shows how a structue
template that defines an invoice number and invoice amount
can be created. The keyword struct tells the compiler that a
structure template is being declared.
Notice that the structure declaration is terminated by a
semi-colon. This is because a structure declaration is a
statement. Also, the structure tag invoice identifies this
particular data structure. At this point in the code, no
variable has been declared; only the form of the data has
To declare a variable, you need to use the following
This defines a structure variable of type 'invoice', called
Inv1. When you declare a structure, you are, in essence,
defining a data type. Memory is not allocated for a
structure until a variable of that type is created.
The compiler automatically allocates sufficient memory to
accommodate all the elements that make up the structure.
You may also declare two or more variables at the time of
declaring a structure. For example:
will declare a structure type called invoice and declare the
variable Inv1 and Inv2.
If only one structure has to be declared in a program, then
following definition would suffice:
The general form of a structure declaration is:
where <tag> is the name of the structure declaration,
effectively the name of the new data type. The structure tag
is then used to declare structure variables. <struct vars>
are the names of structure variables. Either the <tag> or
the <struct vars> can be omitted, but noth both.