I'm just starting to learn classes and I want to initialize null-terminated char array inside a class, but I'm doing it wrong:
1 2 3 4 5 6 7 8 9 10 11
//assume the class is in a header
class SomeClass {
char test[10] = {'\0'};
public:
void SetTest(char ch, int i) {
test[i] = ch;
}
char GetTest(int i) {
return test[i];
}
};
Well I actually want to avoid that, but if there's no other way... I'm not using char array for text (words and such), but for array of single chars, which have no direct relation to each other.
Is it generally bad to use char arrays? If yes, then why?
Is there any known reason why you can't assign values directly in a class? I don't see any reason myself, since nothing has "physical" existence until you create an object, but I know there must be a good one.
Does assigning a value to a whole array with a loop uses same amount of resources as assigning it the way I wrote above? Is there actually any big difference between the two in the "core"?
Sorry for so many questions, but the more I know the better.
P.S. Would using a vector of chars instead of char array create a null-terminated vector automatically?
Is it generally bad to use char arrays? If yes, then why?
If the intent is a string, then it is generally much easier to use std::string than char arrays.
Is there any known reason why you can't assign values directly in a class?
The short and simple answer is that the standard does not allow it.
Does assigning a value to a whole array with a loop uses same amount of resources as assigning it the way I wrote above?
Yours is not legal C++ in that context, so the question cannot be answered meaningfully.
Would using a vector of chars instead of char array create a null-terminated vector automatically?
std::vector<char> v( 10 ); creates a vector of 10 characters, all defaulted to \0. However std::string
is a better alternative to std::vector<char> if the intent is to hold a string.
Assuming you initialize i to 0... Memory and stability wise, no, they are identical.
CPU wise is harder to say. It depends on your compiler and optimizer. I would
not concern myself with it though, as the difference is not likely to be noticeable
even if you ran the code hundreds of thousands of times.