Skip to main content

Section 14.6 Typedefs

C++ data types can sometimes become a bit much to efficiently read or type:
  • vector<vector<int>> - a two dimensional vector of integers
  • vector<vector<int>>::iterator - an iterator over a two dimensional vector of integers
  • map<char, vector<string>> - a map of characters to vectors of strings
To make it easier to read and write, we can use a typedef. A typedef is a way to give a new name to an existing type. The new name can be shorter or more descriptive.

Subsection 14.6.1 Defining a Typedef

The basic syntax for defining a typedef is:
typedef EXISTING_TYPE NEW_NAME;
For example, we could give the name Matrix to the type vector<vector<int>> like this:
typedef vector<vector<int>> Matrix;

Note 14.6.1.

It is a common convention to capitalize new data types or names for data types. That way, when you see Matrix you can guess it is the name of a type of data, not the name of a piece of data.
A typedef like this would normally go outside of any particular function near the top of a code file so that it is available everywhere in that file. If we are building a program with multiple files and want to use the same typedef across many of them, we would write it in a .h file or module that gets included in all the places it is needed.
Figure 14.6.1. If library.h declares a typedef, it will be usable in all files that include library.h.

Subsection 14.6.2 Using a Typedef

Once we have made the typedef we can use Matrix instead of vector<vector<int>> in our code. So the function that takes a two dimensional vector of integers could be written as:
void foo(const Matrix& m);
The new name and the old are interchangeable - they are just different names the same type of thing. So it is perfectly legal to mix and match the names when working with items of that type:
Listing 14.6.2.
// IntTable is a type alias for vector<vector<int>>
typedef vector<vector<int>> IntTable;
// Make a 2D vector
vector<vector<int>> table = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Use type alias to make a reference
IntTable& table2 = table;
It should be noted that overusing typedef can make code less readable. Especially if it is used to assign new names to simple types. Don’t use typedef to make Decimal mean double!

Checkpoint 14.6.1.

Which statement best describes what a typedef does?
  • It is used to declare a variable of a particular type.
  • Typedefs are used to give names to data types, not individual variables. We then use the defined type to declare variables later.
  • It gives an alternative name to an existing type.
  • It defines a new type of data.
  • A typedef is always based on an existing type.
You have attempted of activities on this page.