0

I'd be happy to take a reference if this has been addressed elsewhere.

What is the best practice for including #defines in the current class header files (.h) versus the #defines in .h files of a contained class?

For example: In my A.cpp file:

 A::A(){
      B bObj(A_DEFAULT_WIDTH,A_DEFAULT_HEIGHT);
    }

In my A.h file:

#define A_DEFAULT_WIDTH 10
#define A_DEFAULT_HEIGHT 10
#include "B.h"
class A{
private:
public: 
  A();
};

In my B.h file:

#define B_DEFAULT_WIDTH 10
#define B_DEFAULT_HEIGHT 10
class B{
   private:
     int width;
     int height;
   public:
      B(int,int);
};

In my B.cpp file:

B::B(int inWidth, int inHeight){
  width = inWidth;
  height = inHeight;
}

Clearly I could just use the #defines from B in the A class, but is it better to replicate these #defines in A to keep A better abstracted, or is it better to use the B defines and get rid of the A #defines so that the replicated #defines in A don't cause confusion and get out of sync?

gorlux
  • 129
  • 5
  • Your last paragraph is unclear, what would "get out of sync" ? Is there meant to be some relationship between A's defaults and B's defaults? – M.M Feb 12 '21 at 22:23
  • Yes. If I want the defaults to be the same, then later change them in A but not in B I could get unexpected results if another class calls B and uses the B defaults. – gorlux Feb 12 '21 at 22:25
  • If there is only meant to be one set of defaults then it would not be a good idea to have "A defaults" and "B defaults" – M.M Feb 12 '21 at 22:41

1 Answers1

3

Best practice is to minimise the use of preprocessor. In this case #define is completely unnecessary. Instead you can declare constants using enum or const . And you might not need to declare them at all.

If the values of the constants are not needed or useful in the header then they probably shouldn't go there. In the example you posted they could go in the same file they are used, and perhaps be omitted entirely, just using the value in the single place where it is used.

If there is only meant to be one set of defaults that is used for both classes, you could define them in a header that is included by both A.cpp and B.cpp (does not need to be included in A.h or B.h)

M.M
  • 138,810
  • 21
  • 208
  • 365