2

I have the following:

data.hpp

#include <stdio.h>
class Data{

private:
    char* input_filename;
    char* csv_filename;

public:
    Data(const char* in_filename,const char* out_csv="output.csv");
};

#endif /* data_hpp */

And data.cpp

#include "data.hpp"

Data::Data(const char* in_filename,const char* out_csv): input_filename(in_filename), output_csv(out_csv)
{}

I get the error:

Cannot initialize a member subobject of type 'char *' with an lvalue of type 'const char *'

How can I initialize two array of chars that are passed in the constructor?

Hector Esteban
  • 1,011
  • 1
  • 14
  • 29

1 Answers1

3

char* is a "pointer to a non-const char".

const char* is a "pointer to a const char".

You can't assign a const char* to a char*, which is what the compiler is complaining about. So, you will have to either:

  • change the char* members to const char*:
class Data{

private:
    const char* input_filename;
    const char* csv_filename;

public:
    Data(const char* in_filename, const char* out_csv = "output.csv");
};
#include "data.hpp"

Data::Data(const char* in_filename, const char* out_csv):
    input_filename(in_filename), csv_filename(out_csv)
{}
  • change the char* members to std::string:
#include <string>

class Data{

private:
    std::string input_filename;
    std::string csv_filename;

public:
    Data(const char* in_filename, const char* out_csv = "output.csv");

    /* you can optionally change the constructor parameters to std::string, too...
    Data(const std::string &in_filename, const std::string &out_csv = "output.csv");
    */
};
#include "data.hpp"

Data::Data(const char* in_filename, const char* out_csv):
    input_filename(in_filename), csv_filename(out_csv)
{}

/* or:
Data::Data(const std::string &in_filename, const std::string &out_csv):
    input_filename(in_filename), csv_filename(out_csv)
{}
*/
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770