Can't access protected member variables of the most base class through std::unique_ptr in diamond

给你一囗甜甜゛ 提交于 2019-12-02 12:17:46
Christian Hackl

Both virtual inheritance and std::unique_ptr are red herrings. The problem comes down to this:

class Base
{
protected:
    int m_x;
};

class Last : public Base
{
public:
    Last()
    {
        Base base;
        base.m_x = 0; // error
        m_x = 1; // no error
    }
};

The error is something like error C2248: 'Base::m_x': cannot access protected member declared in class 'Base' or error: 'int Base::m_x' is protected within this context.

The explanation is that protected is a somewhat special case. It does not only work on class level but also on the object level. And you have two relevant objects here:

  1. The Last object which is being created by the constructor, i.e. the one pointed to by this. It's also a Base object because of the is-a inheritance relationship.
  2. The local object named base within the constructor.

Now, the problem is that in the line base.m_x = 0;, you are in the context of the first object and not the second one. In other words, you are trying to access the m_x of base from outside base. C++ simply does not allow this.

A very technical explanation can be found in the C++ standard at §11.4 [class.protected], a more easily understandable one in an excellent answer here on Stack Overflow.

Martin Bonner

protected doesn't mean quite what you think it does.

Although Last is derived from Base, member functions of Last don't have access to the protected members of any Base object - just those Base objects that are sub-objects of some Last object.

So you can write: this->Base::x because *this is a Last object, but not m_p->x, because *m_p is of static type Base.

As others have noted, I think this is actually an XY problem. Having an object which derives from two classes, and then also has a pointer to another object of one of those classes is very strange indeed. I think you need to clarify what you are trying to do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!