Search code examples
c++c++11auto

C++ 11 initialization with auto


In C++ 11, we're encouraged to use auto for variable type,
does this also apply when initializing type like class and vector?

I mean should we write the following:

auto a = 10; 
auto b = MyClass();
auto c = vector<int>{1, 2, 3}; 

instead of:

auto a = 10;
MyClass b;
vector<int> c = {1, 2, 3}; 

Solution

  • auto is just a handy shortcut to simplify things like

    VeryLongClassName *object = new VeryLongClassName();
    

    Now it will be

    auto *object = new VeryLongClassName();
    

    There is no reason to write

    auto a = 10; 
    auto b = MyClass();
    auto c = vector<int>();
    

    because it is longer and harder to read than

    int a = 10;
    MyClass b;
    vector<int> c;