简体   繁体   中英

How do you use std::make_shared to create a smart pointer of a base class type?

What am I doing wrong here? I cannot believe the below doesn't compile. Do you need to use a shared pointer cast or something?

struct Base
{
};

class Child : Base
{
};

int main()
{
    std::shared_ptr<Base> p = std::make_shared<Child>();
}

The error I get with Microsoft compiler is

error C2440: 'initializing': cannot convert from 'std::shared_ptr<Child>' to 'std::shared_ptr<Base>'

It does work. It's just that Base has private inheritance.

struct Child : Base{};

or

class Child : public Base{};

are fixes. Interestingly std::static_pointer_cast and company do exist; but you don't need them here. See https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast

Although @Bathsheba 's and @divinas 's answers solved this issue, none of them explained why is this the solution, and I think it's important for future viewers to know why is it the problem in this case.

When you are trying to create a pointer to the base class Base you are trying to get an access to all of the public members of the base that belong to the derived class (in this case Child ). If the derived class privately inherit the base class (or protected inherit it), all of the members that labeled as public in the base class, inside the derived class now labeled as private (or protected). Which means that the attempt to access them as public members will raise an access privileges violation issue. Because the access privileges is known at the compile time, this is a compilation error.

The solve, as mentioned in previous responses, is to inherit the base class using public inheritance. Which is the default inheritance in struct s and non-default inheritance in class es.

You should use public inheritance instead:

class Child : public Base
{
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM