Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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>'
like image 567
Harjit Singh Avatar asked Dec 02 '22 09:12

Harjit Singh


1 Answers

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

like image 174
Bathsheba Avatar answered Jun 02 '23 14:06

Bathsheba