2

I have a code a following (simplified version):

#define MESSAGE_SIZE_MAX 1024
#defined MESSAGE_COUNT_MAX 20

class MyClass {
public:
   .. some stuff
private:
   unsigned char m_messageStorage[MESSAGE_COUNT_MAX*MESSAGE_SIZE_MAX];
};

I don't like defines, which are visible to all users of MyCalss.

How can I do it in C++ style?

Thanks Dima

dimba
  • 26,717
  • 34
  • 141
  • 196

2 Answers2

7

Why don't you simply use a constant?

const int message_size_max = 1024;

Note that unlike C, C++ makes constant variables in global scope have static linkage by default.

The constant variable above is a constant expression and as such can be used to specify array sizes.

char message[message_size_max];
avakar
  • 32,009
  • 9
  • 68
  • 103
  • It will be statically linked in all objects using MyClass and thus adding garbage to them. – dimba Jul 22 '09 at 15:33
  • If it does, then you have an ancient compiler or you're taking the constant's address somewhere. – avakar Jul 22 '09 at 15:46
6

The trick to get such things into the class definition is,

// public:
enum {MESSAGE_SIZE_MAX=1024, MESSAGE_COUNT_MAX=20};

I never liked #defines to be used like constants.
Its always a good practice to use enum.

nik
  • 13,254
  • 3
  • 41
  • 57