C++11 is the latest version of C++ language originally designed by Stroustrup. I read an interview of him where he said that the latest standard (C++11 or C++0x) feels like a new language.
I will be publishing the new features added to the core language and to the STL in following articles in next few days. The first change (in the core language) which I want to focus today is the introduction of automatic type detection.
1. Automatic Type detection (or Type Interface)
Till the last standard (C++03) we must to specify the data type of the object we are defining.
In C++11, if the data type of the object can be derived from the initialization, then we can declare it as auto (thus defining an object without explicitly mentioning its type).
For example, in the below declaration:
auto a = 10;
Data type of a will be int, because that is what we are initializing it with.
such automatic typing comes very handy when the data type is very verbose (long and difficult to read), like below code of C++03
void func(const vector<pair<string,int>> &va) { vector<pair<string, int>>::const_iterator ca=va.begin(); }
void func(const vector<pair<string,int>> &va) { auto ca=va.begin(); // using auto }
The type of iterator was well defined by the value it is being initialized with.
Another addition to the language is the keyword decltype, which can be used to determine the type of expression at compile time.
int a = 10; decltype(a) b = 20;
void func(const vector<pair<string,int>> &va) { decltype(va) ca=va.begin(); }
I will be covering more new features of C++ in later articles. Let me know your feedbacks / comments / questions. 🙂
Note: The auto is different from the auto keyword which was available in earlier versions (and in C language) that talks about the scope of an object to be automatic and is available in C & C++ since Pre-ANSI era. C++11 has actually removed the old meaning of auto to avoid confusion. auto now declares an object whose type is deducible from the initializer.
4 Responses