I am using wxWidgets where, if you have ever used it, you will know that there are a lot of public functions in the base class. I recently ran into a situation where I would not want a method SetText() be called directly from the derived class. That is, the derived class inherited the SetText() function but I do not want this function to be available to clients. Instead, I am providing two new functions which call SetText() but not before some extra operations are performed.
Currently, the client (me!) can forget to call the special functions and simply call SetText(). Consequently, some extra operations will not be performed. These operations are subtle enough that it may be overlooked easily.
So, can I mark individual functions as private so that the client cannot possibly call them OR simply make it impossible for clients to call it directly (they will have to use my functions to call it indirectly)?
Note that SetText() is not virtual.
EDIT: To future programmers who stumble on this question, check both the marked answer and Doug T.’s answer.
There are actually two ways of doing this. Doug T. gave a very good overview of the first one – using private/protected inheritance and composition – so I won’t go into that one.
The problem with using private/protected inheritance is that it masks everything. Then, you have to selectively expose the members that you still want to be public. If you want most everything to remain public, and are only trying to mask out a single thing, then this can become a major headache. This gives rise to the need for the second way to do this – with the
usingkeyword.For example, in your case, you could simply declare your class as follows:
This only masks the SetText method!
Just remember though, a pointer to a
Childcan always be cast to a pointer to aParent, and access that method again becomes possible – but that’s a problem with inheritance, too:Attempting to access
SomeMethodon an instance ofChildUsingproduces (in VS2005):However, attempting to access either
SomeMethodorAnotherMethodon an instance ofChildPrivateInheritanceproduces: