C++ 'Using' vs 'Typedef'C++ has two keywords that can be used to define new types: typedef and using. Both of these keywords allow you to create a new type name that can be used to declare variables, but they work in slightly different ways. typedef is an older keyword that has been part of the C++ language since the beginning. It is used to create a new type name that is an alias for an existing type. For example, you could use typedef to create a new type named MyInt that is an alias for the built-in int type: SyntaxAfter this definition, you can use MyInt to declare variables just like you would use int: SnippetUsing is a newer keyword that was introduced in C++11. It works in a similar way to typedef, but it has a more flexible syntax and can be used in more places in your code. For example, you can use using to define a new type name in the same way as typedef: SnippetThis creates a new type named MyInt, which is an alias for the built-in int type. You can then use MyInt to declare variables just like you would use int. In general, using is considered to be a more modern and flexible way to define new type names in C++. typedef is still supported for backward compatibility, but the newest code should use using instead. Here is an example of using the using keyword to define a new type named MyInt that is an alias for the built-in int type: C++ code (Example-1)This code will print the following output: x = 5 Note that using is not limited to defining type aliases for built-in types like int. You can use it to define type aliases for any type, including user-defined types, template types, and more. C++ code (Example-2)Output: Size: 10 Capacity: 10 Size: 9 Capacity: 10 Size: 0 Capacity: 10 In this code, we create a 'vector' object that can hold a sequence of integers. We then add some elements to the vector using the 'push_back' method and print its size and capacity. Next, we remove the last element from the vector using the 'pop_back' method and print its size and capacity again C++ code (typedef example)Output: 10 20 30 In this code, we use the 'typedef' keyword to create an alias called 'IntVector' for a 'vector' of integers. We then use this alias to create a 'vector' object and add some elements to it. |