i have an inheritance struct A : public B
, i want to hide individual functions from B, is this possible?
i know the opposite is possible using using BMethod
in the A declaration.
cheers
i have an inheritance struct A : public B
, i want to hide individual functions from B, is this possible?
i know the opposite is possible using using BMethod
in the A declaration.
cheers
You can't "hide it" per se, but you can make it a compile time error to call it. Example:
Examples on codepad with the error, and without.
That all said, despite this being possible, you really shouldn't do it. You'll confuse the hell out of clients.
EDIT: Note that you can also do this with virtual functions (And with the error).
The
using
keyword can be used to change visibilityThere is an issue here: this would be a direct violation of the Liskov Substitution Principle, namely
A
would not act as aB
any longer.If you wish to reuse
B
implementation, the solution is simply to do so:Don't abuse inheritance, use composition instead
To those that are suggesting composition... this might not be the best possible way of going about things. My understanding is that the Liskov Substitution Principle only states that there's the possibility of the functions from the base class being used on the child, not that they necessarily should be. For example, for a particular base class you may have multiple functions that essentially perform the same operation, but for different specific cases. In the derived class you may want to abstract these public functions away in favor of simplifying the user's interface. This is where private inheritance can be used. Private inheritance might also be a necessity, if we have protected functions in the base class that we don't want the user of the base class to call, yet would be invaluable to the derived class.
In short, if you HAVE to, use private inheritance, but composition is preferred in most cases.
Aside from the ways described in the previous answers—composition, private inheritance, and non-private inheritance but with the inherited method declared private—another way is to explicitly
delete
the inherited method:Although the
b.foo()
call produces a compiler error, client code can still call the base class’s version by qualifying with the base class identifierA
:This explicit deletion way works when
foo
is not a virtual non-deleted method inA
. By C++11 Standard §10.3/16, this explicit deletion is ill-formed when the deleted method in the derived class overrides a virtual non-deleted method of the base class. For more info on this restriction, see the answers to the SO question C++11 Delete Overriden Method.If the methods are private in B, then they will remain hidden to a even if you use public inheritance.