Warrior Tang (tangaroa) wrote in cpp,
Warrior Tang

Exposing some class methods while hiding others

class UsefulClass  {
	usefulReadOnlyMethod(); // run me plz
	undesirableMethod();  // hide from coders 

class HasANotIsA {
	safeWrapper(){ foo->undesirableMethod(); } 

	UsefulClass foo; 

I want code using HasANotIsA to be able to run foo->usefulReadOnlyMethod() but not foo->undesirableMethod(). I can put the usefulClass in protected to hide the undesirable method, but that also hides the useful method. I can't take the UsefulClass out of protected and make it public without exposing the undesirable method.

Is there an alternative to wrapping every useful function inside HasANotIsA? That feels like a waste of time and would clutter up the class definition.

It seems that I want to change which methods of UsefulClass are public and which are private, which suggests I should extend the class, add a few wrappers where things change, and put the wrapperMethod in the extended class. I could then make the neutered class public in HasANotIsA. However, it is likely that future code could reach undesirableMethod() by implicitly casting it back to a UsefulClass during a general-purpose routine that has the most basic class as a parameter. Can this be avoided or discouraged?

To be more specific, "UsefulClass" is the STL vector and I want to avoid code that uses STL methods to modify its contents. The safewrapper() is to ensure nothing gets added or removed without a corresponding removal or add to another vector, like in double-book accounting.

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.