Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 344
Hector Esteban Avatar asked Oct 14 '25 13:10

Hector Esteban


1 Answers

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)
{}
*/
like image 125
Remy Lebeau Avatar answered Oct 17 '25 02:10

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!