Search code examples
c++c++17shared-ptr

No matching constructor for initialisation of const std::shared_ptr<>


Scenario
I am using C++ 17 on MacOS with clang as compiler. I have a few classes which are initialised in a certain order demonstrated in sample code below

Firstly, SomeClass which is very simple and almost a dummy for the example sake.

SomeClass.h

SomeClass {

public:
    SomeClass() { }
}

Lets say below is ClassA like this .

ClassA.h

ClassA {

public:
    ClassA(const std::shared_ptr<SomeClass> & some_class);

private:
    std::shared_ptr<SomeClass> m_some_class;
}

ClassA.cpp

ClassA::ClassA(const std::shared_ptr<SomeClass> & some_class) : m_some_class(some_class) {

}

Note above that ClassA intakes a const std::shared_ptr<SomeClass> & type into its constructor and stores it as its member.

Next there is ClassB which has private member of ClassA as std::shared_ptr. And all I want to do is to initialise m_class_a by passing it the required const std::shared_ptr<SomeClass> & which ClassA needs to init its member.

ClassB.h

ClassB {

public:
    ClassB(const std::shared_ptr<SomeClass> & some_class);

private:
    std::shared_ptr<ClassA> m_class_a;
}

ClassB.cpp

ClassB::ClassB(const std::shared_ptr<SomeClass> & some_class) : m_class_a(some_class) {

}
// Above constructor throws compiler error complaining "No matching constructor for initialisation of `std::shared_ptr<SomeClass>`"

And finally, heres my main.cpp which only wants to initialise ClassB

main.cpp

int main(int argc, char *argv[])

    auto some_cass = std::make_shared<SomeClass>();
    ClassB object_b(some_class);
    return 0;
}

Question:
What is wrong with what I am doing above and what is reason for this compiler error? How can I resolve the issue?

Secondary question:
What would change if in ClassB, instead of having std::shared_ptr<ClassA> m_class_a as member, I would have had ClassA & m_class_a as member?


Solution

  • Your issue is that you are trying to initialize a variable with type std::shared_ptr<ClassA> but you are giving it a std::shared_ptr<SomeClass>. They are incompatible.

    Are you trying to create a new ClassA? In that case, the constructor should be:

    ClassB::ClassB(const std::shared_ptr<SomeClass> & some_class)
    : m_class_a(std::make_shared<ClassA>(some_class))
    {}