2
class MyString {
private:
    char *m_pchString;
    int m_nLength;
public:
    MyString(char* pchString="0") {      //problem on this parameter
        m_nLength = strlen(pchString)+1;
        m_pchString = new char[m_nLength];
        strncpy(m_pchString, pchString, m_nLength);
        m_pchString[m_nLength-1] = 0;
    }
    ~MyString() {
        delete[] m_pchString;
        m_pchString = 0;
    }
    char* GetString() {return m_pchString;}
    int GetLength() {return m_nLength;}
};

If I complied this, the compiler will send me a warning:

warning: deprecated conversion from string constant to 'char*'

unless I modify the parameter from char *pchString = "0" to const char *pchString = "0"

Why is the default char* in a parameter must be const?

Juen Khaw
  • 161
  • 1
  • 1
  • 10

3 Answers3

6

Because string literals like "some string" are immutable, and trying to modify one (you can attempt to modify them if passing via non-const reference) leads to undefined behaviour. That's why the standard C++ deprecated this conversion.

Try this for fun (but pls not in production code), live here:

#include <iostream>

int main() 
{
    char* str = "test";
    str[0] = 'w';
    std::cout << str; // oops
}

Related: Why are string literals const?

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
0

When you use a string literal, such as "0", it is put in the read only parts of the program. Making any changes to such data leads to undefined behavior. By trying to initialize a variable of type char* to a sting literal, you are allowing the possibility of the read only data to be modified. That's what the compiler is complaining about.

It's similar to:

const int num;
int* ptr = &num;  // Wrong
R Sahu
  • 204,454
  • 14
  • 159
  • 270
-3

The reason being that char* is considered a outdated practice compared to using the string class.

Nick Krause
  • 1
  • 1
  • 8