开发者

Access specifier while overriding methods

Assume you have a class开发者_Python百科 that defines virtual methods with the access specifier public. Can you change the access specifier on your overriden methods? I am assuming no. Looking for an explanation.


The answer is: sort of. You can only change the access of members the derived class has access to. The type of inheritance has no effect - this only controls the default access for inherited members (to a point, following other rules).

So, you can make a base class's protected members public or private; or a base's public members protected or private. You cannot, however, make a base's private members public or protected.

Example:

class Foo
{
protected:
        void protected_member();

private:
        void private_member();

public:
        void public_member();
};

class Bar : private Foo
{
public:
        using Foo::protected_member;
        using Foo::private_member;
        using Foo::public_member;
};

int main(int, const char**)
{
        Bar bar;

        return 0;
}

The above code elicits the following error on g++ 4.1.2:

main.C:7: error: 'void Foo::private_member()' is private

main.C:14: error: within this context

Additionally, overriding has nothing to do with changing the access of a method. You can override a virtual private method, you just cannot call it from a derived class.


Yes you can, but it "doesn't grok".

Take a look at Overriding public virtual functions with private functions in C++


You definitely can. But it makes no sense. If it is a public inheritance, then you can always cast an object to its base. If it's a private inheritance, all base methods are already private by default. In case of protected inheritance you can make the base method private, so you prevent possible derived classes from calling it, but I don't really understand why one might need it.


Yes you can, and in fact you don't even need to override or use virtual anything.

class ABC {
public: // or this may be protected, no difference
    void woof();
    void moo();
};

class D : private ABC { // now woof and moo are private
public:
    using ABC::woof; // using declaration to make woof public again
    ABC::moo; // access declaration (deprecated) does the same
};

The same works if they are virtual, too. Or, as others noted, virtual function lookup ignores the access specified by the implementing class; any class you can cast to may provide access at compile time.

On the other hand, without the special declarations in D, the public interface of ABC would indeed be inaccessible through D because you wouldn't be able to upcast to ABC. And if woof and moo were virtual, you would want to make the overrides private to hide them. Perhaps that better answers the question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜