I came across a question while taking iKM test. There was a base class with two abstract methods with private access specifier. There was a derived class which was overriding these abstract methods but with protected/public access specifier.
I never came across such thing where overridden methods in derived class had different access specification. Is this allowed ? If yes, does it comply to "IS A" relation between base and derived (i.e. safely substitutable).
Could you point me to some references which can provide more details on such usages of classes ?
Thank you.
Yes, this is legal, accessibility is checked statically (not dynamically):
Now, why would you want to do that? It only matters if you use the derived class
B
directly (2nd param off()
) as opposed to through the baseA
interface (1st param off()
). If you always use the abstractA
interface (as I would recommend in general), it still complies to the "IS-A" relashionship.As many of the guys pointed out it is legal.
However, "IS-A" part is not that simple. When it comes to "dynamic polymorphism" "IS-A" relation holds, I.e. everything you can do with Super you can also do with Derived instance.
However, in C++ we also have something that is often referred as static polymorphism (templates, most of the time). Consider the following example:
Now, when you try to use "dynamic polymorphism" everything seems to be ok:
... but when you use "static polymorphism" you can say that "IS-A" relation no longer holds:
So, in the end, changing visibility for method is "rather legal" but that's one of the ugly things in C++ that may lead you to pitfall.
It is allowed, in both directions (ie, from
private
topublic
AND frompublic
toprivate
).On the other hand, I would argue it does not break the IS-A relationship. I base my argument on 2 facts:
Base&
(orBase*
) handle, you have exactly the same interface as beforepublic
and calling theprivate
method directly anyway: same effect with more typingYes, this is allowed as long as the signature is the same. And in my opinion, yes, you're right, overriding visibility (for example, public -> private) breaks IS-A. I believe Scott Myers Effective C++ series has a discussion on this one.