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

Viewed 275

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>'
3 Answers

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 structs and non-default inheritance in classes.

You should use public inheritance instead:

class Child : public Base
{
};
Related