1

Whenever I try this code to catch class type as exception I get an error message as "deprecated conversion from string constant to 'char*'" .

Why is it so and how can it be avoided?

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class Error
{
 int err_code;
 char *err_desc;
public:
       Error(int c , char* p)
        {
           err_code=c;
           err_desc=new char(strlen(p));
           strcpy(err_desc,p);
        }
        void display(void)
         {
           cout<<err_code<<"done successfully"<<err_desc;
          }
      };
 int main()
{
int x;
try
 {
  cout<<"\n press any key to avoid exception except 99";
  cin>>x;
  if(x=99)
  throw Error(x,"Exception");
 }
catch (Error e )
 {

   cout<<"\n exception caught successfully";
   e.display();
  }

  return 0;
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Zuhi
  • 153
  • 2
  • 2
  • 10

2 Answers2

1

A string literal should be passed into a const char* not a char* (the former is the correct type) so change the constructor signature to

Error(int c , const char* p);

and the member variable to

const char *err_desc;

Or you can pass around std::string, which I would recommend.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

In C++, the type of a string literal is array of const char, so normally you would use it to initialize a const char*, not a char*. The special rule that you can nonetheless initialize a char* with a string literal, which is not really const-correct, is for backward compatibility with C, in which string literals are arrays of plain char. It was deprecated as of C++03, and removed in C++11.

You should change err_desc and the argument of Error's constructor from char* to const char*, which will make the warning go away, as well as make your code const-correct and prevent it from breaking in C++11.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312