C++ Blog

C++0x Auto Types

Posted in c++0x by Umesh Sirsiwal on January 5, 2009

This is part of C++ Reference series.

Several OO languages including SmallTalk, Python, Ruby, etc have a way to creating new variables with the type of existing variables. In C++ to create a variable, the program always had to know the type.

Starting C++0x this restriction goes away. C++0x adds support for auto-types. For example it is now possible to code:

auto a = b->c;
auto a(b->c);

Both these statements will create a variable ‘a’ with type b->c and assign it value of b->c.

No need to  know the type of b->c. Why do we need autotypes. We thought type safety is important. Let us consider the following code segment:
for (std::vector<int>::iterator it= vi.begin(); it!=vi.end(); ++it)

with auto types this simplifies to:
for(auto vi::iterator it = vi.begin(); it  != vi.end; ++it)

Significantly less verbose and more maintainable code. We can change type of vi from vector to list, deque, etc. without changing type of every iterator.

The code no longer cares about type of vi. It just declares an iterator of the type vi::iterator.

In addition, for memory allocation it is now possible to say:

auto* a = new auto(b->c); // new object of the type b->c and assign it to a new variable of type pointer to b->c.

More interesting syntax:

auto p = std::string("xxx"); // p has type of std::string
auto p[] = "xxx"; // p has type of char[4]
auto* p = "xxx"; // p has type char*
auto a = 10; // a has type integer