If I create my class like this:
class MyCLass {
private:
char name[25]{};
public:
MyClass();
MyClass(char name[]);
};
MyClass::MyCLass() {
stringCopy("", this->name);
}
MyCLass::MyClass(char name[]) {
stringCopy(name, this->name);
}
where stringCopy
is a function I made to copy two char arrays, when I create in the main
function an object MyClass obj("John");
, the name is assigned correctly but I get the following warning: ISO C++11 does not allow conversion from string literal to 'char *'
, so I asked myself: What is the correct and best way to initialize a char array as a class member?
First of all, I don't like the way I initialized char name[25]{};
but the only alternative would be to use dynamic memory. Is there a better alternative than the two?
Also, although the message I get after compiling the code is only a warning, I'd rather avoid such potential conflicts in my code. Is there another way to avoid this problem other than creating a char array with the name and then creating an object and passing this new variable as an argument?
EDIT: I missed that detail: I am required to use a char array. No strings are allowed.
Given the advices in the comments, you would probably go with something along:
There is not point in using a
StringCopy()
function for this kind of copy, the functions in the standard libary do that well already ()