• Advertisement
Sign in to follow this  

Making certain functions public to certain classes only?

This topic is 4723 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
Sign in to follow this  

  • Advertisement