Search code examples
c++classc++11structureauto

Does 'auto' in C++ recognize custom data types?


I wondered if I make a class of my own, and do this:

class my{
/*some things*/
}myobj;

and then

auto newobj = myobj;

Will auto recognize this myobj? Will it work in case of a structure as well?


Solution

  • The answer is Yes, as probably you have checked compiling it. The rules are the same as for template argument deduction. You can always check what type is deduced for given auto variable in IDE or use compiler error for that, example:

    class my{
    /*some things*/
    }myobj;
    
    template<typename T> class TD;
    
    int main()
    {
        auto newobj = myobj;
        TD<decltype(newobj)> td;
    }
    

    produces error:

    main.cpp:14:26: error: aggregate 'TD<my> td' has incomplete type and cannot be defined
         TD<decltype(newobj)> td;
    

    giving you information that newobj is of type my