0

[C/C++] Why I can't assign a constant char pointer to a char pointer?

Hey Community, just started learning C++ 2 days ago, but already have much experience with ANSI-C. Although I don’t learning programming with this plattform, I use it to ask some questions ;) My problem now is the following, let me show this shortened code snipped: class Entity{ private: char* name; public: Entity(const char* name1){ name = name1; } } int main(){ Entity person("Steve"); } But this doesn’t work, because I can’t assign "Steve" which is a (constant) chain of chars to Entity::name which holds a pointer of a char. So I must declare Entity::name as a constant or assign it with a defined range. But that don’t make sense for me. I mean, the string "Steve" is lying somewhere in the memory, so I should pointing to it. But no. Sorry if this is a bit unclear, german is my mother tongue.

7th Jun 2019, 4:50 PM
BraveHornet
BraveHornet - avatar
3 Antworten
+ 4
Your problem is when you do name = name1. name1 is const char* and name is char* and the compiler will tell you that const char* cannot be converted to char*. The reason the conversion cannot be done is because by saying const, you say that the variable will not change but then you put it in a type that can be modified. One solution in your case is to change the type of name to const char*
7th Jun 2019, 5:20 PM
Paul
+ 4
You simply forgot a const! The constructor is ok .. But not the member storing the literal, otherwise you can try to modify a literal through Entity::name which is UB or probably illegal private : CONST char* name; Now you have to modify also the constructor to Entity(const char* n):name(n){}
7th Jun 2019, 8:50 PM
AZTECCO
AZTECCO - avatar
+ 3
I would think about what the benefit is to trying to make your argument const. Is it worth the effort to try to work around that? Personally, I don't think so. I also think that if you are going to be programming in C++, try using string types. char pointers is more of a C thing. You could also try using a const pointer instead of a pointer to a const char: Entity(char* const name1) I'm not sure that is what you are going for, but I figured that I would mention it. Note that const char* name1 is the same as char const *name1, just as a weird piece of trivia.
7th Jun 2019, 7:00 PM
Zeke Williams
Zeke Williams - avatar