Copying in C++
This is a fairly straightforward concept but still one that can cause questions when switching from another programming language. C++ has a couple different conventions for copying variables. The simplest way is to assign the variable you want to copy to the new variable of the same type.
Since the type of variable 'foo' is known, this can allow the compiler to set the type for 'bar' automatically with the keyword auto.
Code Editor
Here, bar is declared as having an auto type; therefore, the type of bar is the type of the value used to initialize it: in this case it uses the type of foo, which is int.
Variables that are not initialized can also make use of type deduction with the decltype specifier:
Variables that are not initialized can also make use of type deduction with the decltype specifier:
The difference between auto and decltype is that auto works on types, and decltype works on expressions. Auto is commonly used in day-to-day programming while decltype is mostly for template code.
As c++ has updated, it has received more modern features seen in other languages like auto and decltype for type inference. It can be daunting to see so many ways to accomplish the same task but it comes down to learning what works in a variety of situations and trying it out!
As c++ has updated, it has received more modern features seen in other languages like auto and decltype for type inference. It can be daunting to see so many ways to accomplish the same task but it comes down to learning what works in a variety of situations and trying it out!