Search code examples
classc++11shared-ptrdeclarationaccess-control

No matching conversion for functional-style cast from 'B *' to 'std::shared_ptr<A>'


I have a simple appliction that tries to initialize a shared ptr.

#include <iostream>
#include <memory>
#include <algorithm>

class A {
public:
    A(){
        std::cout << "default ctor for A" << std::endl;
    }
    ~A(){
        std::cout << "default dtor for A" << std::endl;
    }
};

class B : A{
    B(){
        std::cout << "default ctor for B" << std::endl;
    }
    ~B(){
        std::cout << "default dtor for B" << std::endl;
    }
};



int main()
{

    auto ap = std::shared_ptr<A>(new B());
    
    return 0;
}

I am getting the error

No matching conversion for functional-style cast from 'B *' to 'std::shared_ptr<A>'

in this line auto ap = std::shared_ptr(new B());

What am I doing wrong here?


Solution

  • Class B should be declared like

    class B : public A{
    public:
        B(){
            std::cout << "default ctor for B" << std::endl;
        }
        ~B(){
            std::cout << "default dtor for B" << std::endl;
        }
    };