Warrior Tang (tangaroa) wrote in cpp,
Warrior Tang
tangaroa
cpp

Exposing some class methods while hiding others

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

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

	protected: 
	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

    Error

    default userpic
  • 6 comments