C++ provides us using keyword to create type aliases to existing data types. We can create type alias as shown in below example:

using Age = int;

We can use Age as data type where we want to use int.

Age johnAge = 12;

Advantages of Type Aliases

  1. Gives domain knowledge to the data types. Aliases add contextual meaning to types which make code understandable. For example, aliasing int with Age gives meaning that int means an age.
  2. Makes usage of definition of complex data types easy throughout the code. For example
using ObjectList = std::vector<std::pair<std::string, int>>;
  1. Helps to create platform independent types. For example, C++ libraries provide us fixed width integers which are nothing but type aliases to fundamental data types.

Type Alias Properties

  1. They are scoped. For example, type alias defined in a block is invisible to the outside.
  2. They are not distinct type. For example,
using Age = int;
 
int age1 {12};
Age age2 {age1}; // it would not give any error as both are same type.

So, type alias does not create another type and compiler won’t complain if we do above.

Side note

We may encounter ourselves with typedef use cases in some code. It is an older way of aliasing types which has been taken over by using way of creating aliases.

References

  1. https://www.learncpp.com/cpp-tutorial/typedefs-and-type-aliases/