Reputation: 108
class String
{
private:
static const int SZ = 80;
char str[SZ];
public:
String()
{
strcpy_s(str, " ");
}
String(char s[])
{
strcpy_s(str, s);
}
}
This is the constructor i have written, note the second one
and here I am using it:
String s1 = "yes";
String s2 = "no";
String s3;
This is the error message :
Severity Code Description Project File Line Suppression State Error (active) E0415 no suitable constructor exists to convert from "const char [4]" to "String" rishabh c++ projects F:\rishabh c++ projects\rishabh c++ projects\main.cpp 35
Upvotes: 2
Views: 386
Reputation: 63481
The compiler is telling you there is no implicit cast from your string literal to any of the available constructors. The reason behind this is the types that your class can be constructed with:
String(char s[]);
Note that string literals are constant, as per the C++ standard. That will not be implicitly converted to the non-constant type that your constructor requires. To do that would require const_cast
, but please don't do that!!!
You would also get an error (or at least a warning) if you attempted explicit construction:
String s1("yes"); // error
The simple fix is the change the parameter to const char[]
(or indeed const char*
is more commonly used).
String(const char *s)
{
strcpy_s(str, s);
}
Whenever passing pointer or reference types as parameters, always ask yourself: "does my function need to modify the value of the parameter?" -- whenever the answer is "no" make it const
.
Upvotes: 6