ragedhumancompiler
ragedhumancompiler

Reputation: 1

About the type const char* and the name of the char array

#include <iostream>
#include <cstring>
using namespace std;

class String {
    private :
        const char * str; // declaration "char str[30];" is appropriate
    public :
        String(const char * _str) {
            str = new char[30];
            strcpy(str, _str);
        }
}; 

int main() {
    const char* sz = "Hello!";
    String s("Hi!");
    s = sz;
    return 0;
}

I have a question for the types const char * and char array. What I know is that "the name of a char array" has the same type as "the const char * variable". So, as what i wrote in the above code, I thought it would be compiled properly. But the compiler rejects my code, because the function strcpy() doesn't support conversion from the type const char * to the type char*. What's wrong with this situation? Am I having wrong C++ grammatical knowledge?

Upvotes: 0

Views: 615

Answers (1)

rici
rici

Reputation: 241861

The result of new char[30] is of type char* and you would have no problems copying something to the allocation using strcpy (although it's definitely not something you should be doing, since it's an open invitation to buffer overflow). The problem is that you immediately assign that pointer to str and str has type const char*. const is constant; you can't assign to a const, which is what strcpy will do.

In fact, assigning the pointer to a const char* member doesn't magically change the nature of the memory pointed to. If you were able to call strcpy, for example by const_casting the first argument, then nothing would break. The memory is writable. But the compiler won't let you write to it through a const char* because declaring a pointer to be const char* is a promise that you won't try to write to the memory. And it's a promise which you immediately break.

Anyway, you can do the following, at no extra cost:

class String {
    private :
        const char * str; // declaration "char str[30];" is appropriate
    public :
        String(const char * _str) {
            char * cpy = new char[strlen(_str) + 1];
            str = strcpy(cpy, _str);
        }
};

Upvotes: 1

Related Questions