I have a class with a private char str[256];
and for it I have an explicit constructor:
explicit myClass(const char *func)
{
strcpy(str,func);
}
I call it as:
myClass obj("example");
When I compile this I get the following warning:
deprecated conversion from string constant to 'char*'
Why is this happening?
The worst part about this is the typical ambiguity in the abuse of the reserved word "string," which leads one to believe, wrongly, that "example".c_str() would resolve the issue.
As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
However, if you want to keep your code warning-free as well then just make respective change in your code:
That is, simply cast the
string
constant to(char *)
.For what its worth, I find this simple wrapper class to be helpful for converting C++ strings to
char *
:This is an error message you see whenever you have a situation like the following:
Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from
const char*
tochar*
is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to achar*
and gives you a warning about this conversion being deprecated.So, somwehere you are missing one or more
const
s in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.There are 3 solutions:
Solution 1:
Solution 2:
Solution 3:
Arrays also can be used instead of pointers because an array is already a constant pointer.