xuejieNian
xuejieNian

Reputation: 63

private base class error when using enable_shared_from_this

the following code does not compile:

class A : B, std::enable_shared_from_this<A>
{
public:
    A();
    virtual ~A();
public:
    void initStr(std::string str=""){m_STR = str;};
private:
    std::string m_STR;
};

The error output:

Cannot cast 'A' to its private base class 'const enable_shared_from_this'

the Xcode version is 8.2.1 Apple LLVM version 8.0.0 (clang-800.0.42.1)

who can give some suggest to me? thanks!

Upvotes: 0

Views: 573

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

Change class for struct. struct makes inheritance public by default:

struct A : B, std::enable_shared_from_this<A> {
    A();
    virtual ~A();

    void initStr(std::string str = {}) { m_STR = str; }

private:
    std::string m_STR;
};

Alternatively, you can also specify a class to extend publicly:

class A : B, public std::enable_shared_from_this<A>
{
public:
    A();
    virtual ~A();
public:
    void initStr(std::string str=""){m_STR = str;};
private:
    std::string m_STR;
};

Upvotes: 2

Related Questions