When you u->favs for u->favs , you get std::string& , and the range is based on what it then starts to repeat after that string one character at a time. Therefore, when you auto you see individual characters from the first line, and when you try to associate this character with string& , you get a compilation error.
You cannot get a range based on working with a pointer type because it does not know how many objects your pointer points to. If you make the following changes to your code to declare favs as an array of static size, then your code will work.
Change the class definition to
using namespace std::string_literals; // allows use of operator""s (user defined literal) class User { public: User() : favs{{"Hello"s, "how"s, "are"s, "you"s, "?"s}} // use operator""s {} // no need for a destructor definition std::string lName; std::string fName; int age; std::array<std::string, 5> favs; // statically sized array };
If you need an array with dynamic size, use std::vector<std::string> instead, and your loop will work.
source share