3

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
liv2hak
  • 14,472
  • 53
  • 157
  • 270
  • https://stackoverflow.com/questions/9661936/inheritance-a-is-an-inaccessible-base-of-b, in short: `class B : public A{ public:` – rafix07 Jul 22 '21 at 10:06

1 Answers1

3

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;
    }
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335