class constructor and string

I've been struggling with creation of proper constructor which takes string as parameter and uses parameter to initialize member of class.
Book I'm reading uses 'string' header and I feel like it's cheating and google gave me init list.

I actually was able to successfully do what I wanted, gcc gave warning tho and I feel like there is better/correct way to do this.

1
2
3
4
5
6
7
8
  class ERROR{
public:
char *data;
ERROR(char*);
};

ERROR::ERROR(char* init) {
data=init; }
What is the warning message and what do you want?
' warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] '

It works as expected but still warning.
And I just want to initialize member string with parameter without using string library.

I know there is way with loops, reassigning member char pointer to desired string address (as did here).

You are not using a "string". Your constructor takes a pointer and your class holds a pointer.

If you do call it ERROR foo( "Hello" ); The calling code has somewhere in memory a literal "Hello\0", and the address to its first char is a const char *. After construction the foo.data points to that same address. That is not a copy of the string.

Obviously, it would be an error to modify any foo.data[i].

You could change the data and init to be const char *. However, you probably should dynamically allocate memory for the content of init, copy the content of init to that memory and set data to point to that memory. Then you should also deallocate the memory pointed to by data in the destructor of ERROR.

Using std::string (or any of std::) is not "cheating"; it lets you concentrate on real "work" rather than trivialities. However, one has to learn to understand the basics too, so playing with "raw bits" has a purpose.
You an try using the const_cast tempate function?

Aceix.
You showed irrelevant code. I think that the problem is in another code where you are trying to create an object of type ERROR and passing a string literal to the constructor.
String literals have type const char[]. So you may not assign a string literal to char *
Topic archived. No new replies allowed.