accessing a protected member of a base class in an

2019-01-06 15:26发布

Why does this compile:

class FooBase
{
protected:
    void fooBase(void);
};

class Foo : public FooBase
{
public:
    void foo(Foo& fooBar)
    {
        fooBar.fooBase();
    }
};

but this does not?

class FooBase
{
protected:
    void fooBase(void);
};

class Foo : public FooBase
{
public:
    void foo(FooBase& fooBar)
    {
        fooBar.fooBase();
    }
};

On the one hand C++ grants access to private/protected members for all instances of that class, but on the other hand it does not grant access to protected members of a base class for all instances of a subclass. This looks rather inconsistent to me.

I have tested compiling with VC++ and with ideone.com and both compile the first but not the second code snippet.

7条回答
干净又极端
2楼-- · 2019-01-06 15:53

The C++ FAQ summarizes this issue nicely:

[You] are allowed to pick your own pockets, but you are not allowed to pick your father's pockets nor your brother's pockets.

查看更多
登录 后发表回答