Department of Engineering

IT Services

C++ typedef

typedef doesn't invent new types. It creates abbreviated names for existing types. Its use is similar in a way to the creation of variables. For example

unsigned int ui;

creates a variable called ui of type unsigned int whereas

typedef unsigned int ui;

creates ui, a shortened way of typing unsigned int. Typing

ui i;

would create a variable called i of type unsigned int. Because it's not creating new types, typedef can't be use to create distinct types. For example, after

typedef unsigned long ul1;
typedef unsigned long ul2;

ul1 and ul2 can be used interchangably.

It's not a facility that beginners are likely to explicitly use, though behind the scenes, the standard library uses it. For example, string is created using this typedef

   typedef basic_string<char> string;

The facility's especially useful when repeatedly using complicated types - e.g. the following creates a pointer type.

typedef iterator_traits<_Iterator>::pointer pointer;

and

typedef void (*func)(int, int);

defines func as the type of a function that returns nothing and takes 2 integer parameters.

C++11 provides another way of doing typedefs, using type aliases. Here's how string could have been defined using this newer facility.

using string = basic_string<char>;