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
- Gives domain knowledge to the data types. Aliases add contextual meaning to types which make code understandable. For example, aliasing
intwithAgegives meaning thatintmeans an age. - Makes usage of definition of complex data types easy throughout the code. For example
using ObjectList = std::vector<std::pair<std::string, int>>;- 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
- They are scoped. For example, type alias defined in a block is invisible to the outside.
- 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
typedefuse cases in some code. It is an older way of aliasing types which has been taken over byusingway of creating aliases.