I’m using the initializer list method for my class constructor. I initialize my variables by calling a getData member function of the dataRegistry Class which provides the data to load into my class’ variables. The getData method is normally called by passing a character array which contains the name of the data to be loaded.
For e.g. an initializer list looks like the following:
dataItem1(dr.getData("Pop.Stats1")),
dataItem2(dr.getData("Pop.Stats2"))
However, due to the way the names of provided, I need to pull the name of the dataset from a user class and then append the variable name to pass to the getData method. Something like this:
datasetName(user.getAttributeString("DataSetName")),
dataItem1(dr.getData(datasetName + ".Stats1")),
dataItem2(dr.getData(datasetName + ".Stats2"))
where datasetName is defined as a std::string variable.
However, this throws the following error:
no matching function for call to 'DataRegistry::GetData(std::basic_string<char,std::char_traits<char>, std::allocator<char> >)'
Since the implementation of the getData method is not provided to me and I know that it works when I just pass a char array (e.g.”Pop.Stat1″) to the function, I suspected this was because the function accepted character arrays only. So, I tried:
datasetName(user.getAttributeString("DataSetName")),
dataItem1(dr.getData(strcat(datasetName.c_str() , ".Stats1"))),
dataItem2(dr.getData(strcat(datasetName.c_str() , ".Stats2"))),
but this throws the error:
error: invalid conversion from 'const char*' to 'char*'
initializing argument 1 of 'char* strcat(char*, const char*)'
I’m clueless as to what’s going wrong? Please advise!
Almost, though using
strcaton the return value ofc_str()causes undefined behaviour. Just do:so the whole line looks like
Because you’re concatenating
".Stats1"ontodatasetNameviastring::operator+, then you want to get theconst char*to that string, so you usec_str()on the return value ofoperator+.You need the parentheses around it because
.has higher precedence than+, so if the parens weren’t there, you’d be callingc_str()on “.Stats1” (instead of the return value of+) which doesn’t exist.