Nasrat Takoor
Nasrat Takoor

Reputation: 354

A value of type const char* cannot be assigned to an entity of type char*?

I have a class like the following (I've deleted extraneous items):

class GL_Texture
{
public:
    GL_Texture();

private:
    char* fileLocation;
};

It's constructor looks like this:

GL_Texture::GL_Texture()
{
    fileLocation = ""; //  error C2440: '=': cannot convert from 'const char [1]' to 'char *'
}

The constructor is producing an error error C2440: '=': cannot convert from 'const char [1]' to 'char *'. Even if I try to make fileLocation a char* const, I get the following error on that line

error C2166: l-value specifies const object

If I cannot assign a string literal to a char*, and I can't qualify fileLocation as pointer to const, how am I supposed to initialize it in the constructor?

Upvotes: 2

Views: 2680

Answers (1)

Joseph Larson
Joseph Larson

Reputation: 9078

You have a few choices:

  1. First, the one most people will agree is the best in most situations: don't use char *, use std::string.

  2. Second, initialize to nullptr instead.

  3. Third: fileLocation = strdup(""); and then clean it up in the destructor. This is ugly.

  4. Fourth: change it to char const *.

Upvotes: 1

Related Questions