Zuhi
Zuhi

Reputation: 163

Error in class type as an exception in c++

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

Upvotes: 1

Views: 49

Answers (2)

Brian Bi
Brian Bi

Reputation: 119239

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.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117886

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.

Upvotes: 1

Related Questions