What is the difference between the line that does not compile and the line that does compile? The line that does not compile gives this warning: deprecated conversion from string constant to 'char*'
Also, I'm aware casting (char *) on the string being passed in to the function would solve the problem, but I would like to understand why that's even necessary when the 2nd line compiles just fine.
class Student {
public:
Student( char name[] ) {
}
}
int main() {
Student stud( "Kacy" ); //does not compile
char name[20] = "Kacy"; //compiles just fine
}
The char[]
signature in the parameter is exactly the same as char*
. In C++, it is illegal to convert a string constant char const*
(the string "Kacy"
) to a char*
because strings are immutable.
Your second example compiles because the name
is an actual array. There is no change to char*
.
As a solution, change your parameter to take a const string array:
Student(char const name[]);
which again is the same as
String(char const *name);
though you're better off using std::string
:
#include <string>
class String
{
public:
String(std::string name);
};