1

I have this constructor for my class student.

student::student( char* rollno ,   char* name , date dob) :
    rollno(rollno), name(name),dob(dob)
{
}

When I write student s1( "l1f18bscs0322" , "usama" , { 13,7,1998 }); in main, it accepts it in my university I think because its using Visual studio 2013, but It gives error in home as I am using visual studio 2019. It says no instance of constructor matches the argument list it takes value in double quotes as pointer to constant. What will be the alternate to pass values to this constructor? Because even If I change my constructor protype to constant to pointer so it will give new error that I cannot initialize my non constant members with constant.

R Sahu
  • 204,454
  • 14
  • 159
  • 270

1 Answers1

7

Because it is!

The type of a string literal, in C++, is const char[N] (where N is the length of the string including its null terminator). That decays to const char*, not char*.

In earlier versions of C++ (pre-2011), you were permitted to "forget" the const for compatibility with C, though doing so was deprecated (and attempting to "modify" the literal had undefined behaviour). Since then you must write it.

You've upgraded to a version of Visual Studio that enforces this rule, possibly only because its default C++ standard is C++11 or later.

It's a good thing; add the const.

If your course material uses char* here, it is out-of-date, and was always "wrong" in a sense.

even If I change my constructor protype to constant to pointer so it will give new error that I cannot initialize my non constant members with constant

You need to do the same thing to your member variables.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
  • But what if I don't want my members to be a constant and I want their value can be changed later? – Usama Javed Nov 30 '20 at 15:53
  • 1
    @UsamaJaved Then you'll need them to be something other than pointers to string literals. A `std::string` would be ideal, if your course permits it. Failing that, there's old-fashioned `strdup` and `free` (but yuck!). That being said, it seems unlikely that you really want to modify individual characters of these strings, and can probably just assign _different_ string literals to the pointers later? We don't know enough about your goal and requirements to make further concrete suggestions at the moment. – Asteroids With Wings Nov 30 '20 at 15:55
  • @UsamaJaved, then you make a copy of the input and store the copy. – R Sahu Nov 30 '20 at 15:55
  • 2
    not the pointers are constant just the "point-to-data". You are not allowed to change "usama" (it is stored in const storage) – Bernd Nov 30 '20 at 15:55
  • Got it, Thank you everyone. – Usama Javed Nov 30 '20 at 15:57
  • @UsamaJaved You bet. Have fun! – Asteroids With Wings Nov 30 '20 at 16:01