0

I am just trying to design a class to set and get the details of a student in C++. So,to set the details of the student,i called set_data(name,roll) method.But this compilation error is coming.I have passed the same data type as actual arguments to the function as expected.I cant understand why error is coming.

G:\>g++ 5.cpp
5.cpp: In function 'int main()'
5.cpp:26:23: warning: deprecate
rite-strings]
 obj.set_data("asdf",15);

The code is ---

#include<iostream>
using namespace std;
#include<string.h>
#include<stdlib.h>      
class pntr_obj
{
char *name;
int roll;
public:
void set_data(char *name,int roll)
{
this->name=name;
this->roll=roll;
}
void print()
{
cout<<"name is "<<this->name<<endl;

cout<<"roll is "<<this->roll<<endl;
}
};
int main()
{
pntr_obj obj;

obj.set_data("asdf",15);
obj.print();
return 0;
}
asad_hussain
  • 1,959
  • 1
  • 17
  • 27

1 Answers1

3

I have passed the same data type as actual arguments to the function as expected.

No. "asdf" is string literal with type const char[5], it might decay to const char*, but not char *.

In C, string literals are of type char[], and can be assigned directly to a (non-const) char*. C++03 allowed it as well (but deprecated it, as literals are const in C++). C++11 no longer allows such assignments without a cast.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405