carloabelli
carloabelli

Reputation: 4349

Using vector Initializer List Constructor with shared_ptr of Derived Classes

I am trying to initialize a vector of shared_ptrs. Unfortunately the following small example does not compile:

#include <vector>
#include <memory>

class Base {};
class Derived1 : Base {};
class Derived2 : Base {};

int main() {
    std::vector<int> v1 = {1, 2, 3}; // no error
    std::vector<std::shared_ptr<Base>> v2{
        std::make_shared<Derived1>(),
        std::make_shared<Derived2>()
    }; // error
}

Why can I create a vector of ints but not of shared_ptrs using the initializer list?

Upvotes: 0

Views: 58

Answers (1)

user2100815
user2100815

Reputation:

Because you are using private inheritance. This compiles:

#include <vector>
#include <memory>

class Base {};
class Derived1 : public Base {};
class Derived2 : public Base {};

int main() {
    std::vector<int> v1 = {1, 2, 3}; // no error
    std::vector<std::shared_ptr<Base>> v2{
        std::make_shared<Derived1>(),
        std::make_shared<Derived2>()
    }; // error
}

Upvotes: 2

Related Questions