Ch2.19: using and typedef

Overview

C++ lets you create type aliases: new names for existing types. Historically this was done with typedef. Modern C++ prefers using, which has clearer syntax and avoids many readability issues.

In this chapter, you will learn:

1. What is a type alias?

A type alias is simply another name for an existing type. It does not create a new type — it only creates a new name.


int x{42};
int y{0};   // same type as x

Type aliases are useful when a type is long, repetitive, or used frequently.

2. typedef — the old way

typedef is the classic C-style way to create a type alias.


typedef int my_int;

my_int x{42};   // x is an int

The syntax is:


typedef existing-type new-name;

This works, but becomes confusing with more complex types.

3. typedef with references

typedef can also alias reference types.


typedef int& int_ref;

int value{42};
int_ref r = value;   // r is an int&

The alias int_ref behaves exactly like int&.

4. using — the modern way

Modern C++ introduces using for type aliases. Its syntax is clearer:


using new-name = existing-type;

Example:


using my_int = int;

my_int x{42};   // x is an int

The new name appears on the left, the existing type on the right — similar to assignment. This makes using easier to read.

5. using with references

Reference aliases are also clearer with using.


using int_ref = int&;

int value{42};
int_ref r = value;   // r is an int&

The & clearly belongs to the type on the right-hand side.

6. Why using is preferred

In modern C++:

For new code, you should always prefer using over typedef.

7. Best practices

Key takeaways