Search code examples
c++constructorstdvectorlist-initialization

how to brace initialize vector of custom class in C++?


Having this simple code:

#include <iostream>
#include <vector>
#include <string>

class Person{
public:
    Person(std::string const& name) : name(name) {}
    std::string const& getName() const {
        return name;
    }
private:
    std::string name;
};

int main(){
//    std::vector<int> ar = {1,2,3};
    std::vector<Person> persons = {"John", "David", "Peter"};
}

I am getting error:

could not convert ‘{"John", "David", "Peter"}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Person>’

So why vector of ints is enabled to brace-initialize, but custom class with implicit constructor (with std::string) cannot? And how to enable it?


Solution

  • You just need more braces:

    std::vector<Person> persons = {
        {"John"}, {"David"}, {"Peter"}
    };