Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
liv2hak Avatar asked Sep 11 '25 15:09

liv2hak


1 Answers

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;
    }
};
like image 187
Vlad from Moscow Avatar answered Sep 13 '25 06:09

Vlad from Moscow