If you don't want to use a magic number in the class and put it outside, #define is not the best way as it has a global effect, that is everywhere that N appears anywhere in the code it will be replaced by 10. You probably want to localise it.
You can do that in a namespace and const size_t declaration within that namespace.
namespace MyModule {
const size_t STRING_ARRAY_SIZE = 10; // you do want the semi-colon
}
class String
{
private:
char str[ MyModule::STRING_ARRAY_SIZE ];
// rest of class
};
If the class String
is in the namespace MyModule you do not need to qualify with ::
within the class. If you want the size limited to within the class you can put it there.
Note that no matter where you put it and how it is defined it must be a compile-time constant. It is not something you can store in configuration as the array size must be known at compile time as sizeof(String)
depends on it.
Incidentally, Strings are commonly implemented with a static array for short strings and a dynamic one for longer strings. For non-mutable strings one will sometimes implement the long strings with some "shared" array. It can make swap()
difficult to implement but it can be more efficient with fewer dynamic allocations.
Your constructor taking char[]
is not a good idea really. Probably should take const char *
.