c++ - Is it bad to not define a static array size in a class?--but rather to let it autosize -
ex: acceptable? compiles , seems work me; bad form?
.h file
class myclass { static char c[]; };
.cpp file
char myclass::c[] = "abcde";
or must instead, example?
.h file
class myclass { static char c[10]; };
.cpp file
char myclass::c[10] = "abcde";
is there benefit 1 technique on other? i'm not sure if i'm missing something. don't know don't know, ya know?
update:
the original code posted looked below. edited make shown above since didn't mean "private" aspect of point of discussion. in real code (running on arduino), using .h , .cpp files , static member intended accessed class. i guess i'm learning new though too, answers regarding below code seem tell me private static members same public static members ie: can both modified outside class if static. that, didn't know. wrong, see answer alok save here. more on static member variables here. line helpful me: "because static member variables not part of individual objects, must explicitly define static member if want initialize non-zero value...this initializer should placed in code file class (eg. something.cpp). in absense of initializing line, c++ initialize value 0."
class myclass { private: static char c[]; }; char myclass::c[] = "abcde";
or must instead, example?
class myclass { private: static char c[10]; }; char myclass::c[10] = "abcde";
the question seems whether explicitly write size of array, rather deduce assignment. consider this:
what if need change string value array initialized to? if explicitly define size, need change in 3 places. first in class definition, second in static variable assignment. , third, end changing value of string assigned. not explicitly writing array size allows make change in 1 place. additionally, eliminates possibility of forgetting add 1 null terminator @ end of string.
clearly, simplifies future code changes , not sacrifice code clarity.
Comments
Post a Comment