0

In the private section of my class there are a lot of functions, let's say there are:

  • 3 functions for purpose A
  • 5 for purpose B
  • 1 for purpose C

I was wondering if it was okay to make a .h file which contains all of the Purpose A functions, one for purpose B and one for C and then include each in the middle of the class definition.

If it's considered bad practice, what is the best way to compact these functions prototypes ?

Matt
  • 1,245
  • 2
  • 17
  • 32
  • See also [here](https://stackoverflow.com/questions/53416657/why-isnt-pragma-once-automatically-assumed/) for some examples of "legitimate" reasons to `#include` in the middle of a file. – Max Langhof Dec 12 '18 at 13:55

1 Answers1

4

Relying on inclusion is a crutch you try to use when you failed to encapsulate those purposes. Write types for them

class PurposeA {
  // Functions
};

class PurposeB {
  // Functions
};

class PurposeC {
  // Functions
};

And then inherit privately, or compose, depending on your needs:

class Foo : private PurposeA,
            private PurposeB,
            private PurposeC {
};

class Bar {
private:
  PurposeA a;
  PurposeB b;
  PurposeC c;
};

Your function bloat is a strong hint your classes carry too much responsibility. Refactoring and encapsulation into smaller and more focused classes will serve to make the overall design better.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Thanks, this seems like a good solution, But you made me ask another question. Since my functions are in class A and rely on class A's variables, i'll need to create class PurposeA, B and C as a child of class A but I won't be able to put them back into class A after that, how do I do ? I'm sorry if this sounds dumb but i'm a begginer –  Dec 12 '18 at 14:16
  • @Matt - You can also pass an `A&` to the members of `B` and `C` that need to operate on A. Anyway, I'd strive to make each class as independent as possible. But there is no one size fits all solution. Only you know your exact problem and possible needs. – StoryTeller - Unslander Monica Dec 12 '18 at 14:19