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.
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.
Return types and access modifiers are not qualifying factors for method overloading.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With