-3

Given the following class:

class S
{
     ...
 private:
     void Action1();
     void Action2();
     .
     .
     .
     void ActionN();
}

The Action functions are related, which are called in the constructor. For logical reason, I want to separate these methods:

class SActions
{
     public:
         SActions(Smthg* s);
     private:
         void Action1();
         void Action2();
         .
         .
         .
         void ActionN();
}

In this case, the SActions s(this);line should be placed somewhere in the S. This two way dependency seems to me a little bit wrong. Is there a good pattern, or solution for this? What kind of workaround should I follow?

  • Are Action1 through ActionN used anywhere besides the constructor? – user1118321 Feb 17 at 17:37
  • Yes, there's a public function in SActions, which calles every Action (sorry, I've missed it from the question). This public function called in the S's constructor. – randomguy Feb 17 at 17:46
  • What SActions s(this); line do you mean? I can't see one. Do the ActionN functions operate on the instance? The accepted answer seems to assume not, but I can't see this stated anywhere. – Useless Feb 19 at 13:42
3

One way to handle this is by not putting Action1() through ActionN() in any class. Simply make them a set of standalone functions. If they're only used by one particular class, as it seems they are, then you can make them static or put them in an anonymous namespace and have them be free functions within S's .cpp file. S can contain a public function performActions() that calls them in order, and it can be called from the constructor.

By not putting them into any class, you don't clutter up the header for that class with a bunch of functions that nobody else can call. This makes it easier to read the header and understand the class. It's an implementation detail that other code doesn't need to know about.

Alternatively, if you don't want the implementation file to be cluttered with functions that aren't part of the class, you can make a second header containing just the free functions prototypes and only include it in S's .cpp file and put the actual functions into their own source file. This reduces clutter in both S's header and implementation files.

  • " then you can make them static and have them be free functions within S's .cpp file" - Using the static keyword for that purpose is deprecated. You should use an anonymous namespace instead. – Christian Hackl Feb 18 at 14:59
  • OK, I've added that as an option in my response. – user1118321 Feb 18 at 21:01
  • Cool. But it's not really an "option" but the default approach. You should only use static for that if you target a very, very old compiler. – Christian Hackl Feb 19 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.