Question

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

}
Was it helpful?

Solution

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);
};

OTHER TIPS

C++ string literals have type "array of n const char", which decays into const char * in your use case. The implicit conversion to char * (that is, discarding the const) you're trying is deprecated, so there's a warning. Change the type in the constructor's signature or make an explicit const-cast.

From the C++ standard:

An ordinary string literal has type "array of n const char" and static storage duration

The string

"Kacy"

is not an array of characters when the compiler produces the code. Instead, it will stash the string "Kacy" somewhere in memory, and produce a pointer to that place. So what you get is a const char * pointing at the string "Kacy\0".

If you change your constructor to:

 Student(const char *nmae)

you can use it both as:

 Student stud("Kacy");

and as this:

 char name[20] = "Kacy"; 
 Student stud2(name);

Note here that the compiler will generate code to FILL the array name with the characters in "Kacy", which is different from just usinv "Kacy" as an argument to the Student constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top