Sign in to follow this  
NeXius

Making certain functions public to certain classes only?

Recommended Posts

NeXius    124
I've often found it useful to some functions from the general users of the class, but expose it to maybe one specific manager like class Friend functions won't help me here since this makes the functions have access to the class rather than the other way around... I think a good way is to make an interface class for the manager class, and then make the manager class a friend of the interface class. Example:
class MainClassManagerInterface
{
private:
   static void MethodMeantToBeUsedWithManager( MainClass& mainClass )
   {
      mainClass.MethodMeantToBeUsedWithManager();
   }
   
   friend MainClassManager;
};

Class MainClass
{
public:
    void GeneralUsageMethod();
private:
    void MethodMeantToBeUsedWithManager();
private: 
    void MyOwnMethod();

    friend MainClassManagerInterface;
};
But I'd like to know if there is a better way, or if this is really very good practice in the first place?

Share this post


Link to post
Share on other sites
hplus0603    11356
Yes, using a special "management" interface is a good solution; we use it a lot with good results.

You don't need to make it friends with anyone; you could make sure that it only ever gets passed to the manager.


class IStuffManagement {
public:
virtual void gropeStuff() = 0;
virtual IStuff * stuff() = 0;
};

class IStuff {
public:
virtual void useStuff() = 0;
};

class IStuffManager {
public:
virtual void setStuffManagement( IStuffManagement * mgmt ) = 0;
};

class IStuffUser {
public:
virtual void setStuff( IStuff * stuff ) = 0;
};


void main() {
IStuffManagement * mgmt = NewStuff();
gStuffManager.setStuffManagement( mgmt );
gSomeStuffUser.setStuff( mgmt->stuff() );
gSomeOtherStuffUser.setStuff( mgmt->stuff() );
}

Share this post


Link to post
Share on other sites
Zahlman    1682
I usually just build the "static/manager interface" into the class itself. ::shrug:: If the interface does enough, you can even privatize the ctors, and have calling code not even have to worry about the existence of those objects. Or you could do it at file scope, too. The class is not the only fundamental unit of encapsulation in C++.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this