Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access specifier while overriding methods

Tags:

c++

overriding

Assume you have a class 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.

like image 750
Pradyot Avatar asked Apr 19 '10 22:04

Pradyot


People also ask

What should be the access specifier of overridden method?

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

Does access modifier affect method overloading in Java?

Return types and access modifiers are not qualifying factors for method overloading.

What are the rules to be followed while overriding a method?

Rules to be followed while overriding methodsBoth methods must have same name, same parameters and, same return type else they both will be treated as different methods. The method in the child class must not have higher access restriction than the one in the super class.


1 Answers

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.

like image 143
Nathan Ernst Avatar answered Oct 14 '22 10:10

Nathan Ernst