Chapter 8: User-Defined Data Types


Download CD Content

Overview

Throughout this book you have been using a variety of different variables of different types (int, float, bool, etc.). However, all these data types have something in common; they each store a single value. That statement may seem so obvious as to not need stating. However, having a variable store only a single value is not the only option you have when programming with C++. Another option is to create user-defined data types. User-defined data types are data types that you create. They allow you to store several, hopefully related, values under a single variable name. You literally create your own new data type. The difference between your data types and the ones that are part of the C++ language is that yours are complex and hold more than one value.

A structure is one of the most common sorts of user-defined data type. That means that you, the programmer, essentially create your own new data type to suit your needs. Structures are just one category of user-defined data types, but they are perhaps the most commonly used. Other user-defined types include typedefs, unions, and enumerations. Each of these user-defined data types will be explored and demonstrated in this chapter. The different categories of user-defined types are summarized in Table 8.1. Each will be explained in detail later in the chapter.

Table 8.1: User-Defined Types

User-Defined Type

Purpose

Example

Structure

A compound data type that simply combines several related pieces of data.

Struct employee
{
char lastname[30];
float salary;
};

Typedef

Provides a different name, or an alias for an existing data type.

Typedef int RETURN;
Typedef double ANSWER;

Union

A combination of different data types.

Union NumericType
{
int
iValue;
long
lValue;
double dValue;
}

Enumeration

An enumeration is a user- defined type that defines named constants.

enum
test{value1,value2,value3};

Bit Field

A type of structure that allows you access to individual bits.

Struct status
{
unsigned :cleartosend;
unsigned :ringing;
}

Table 8.1 shows you the basics of the various user-defined data types. The following sections of this chapter will explore each of these in detail, with examples. The structure is perhaps the most commonly encountered user-defined data type, and it is essential to master it. However, the other user-defined types are also important and should not be ignored.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net