I'm reading data from a file in JSON format, and I want to put the values in the objects password_c and apiKeyValue members:
class Configuration {
private:
char password_c[32];
char apiKeyValue_c[20];
public:
String get_ApiKeyValue();
void set_ApiKeyValue(char* apiKeyValue);
String get_Password();
void set_Password(char* password);
};
String Configuration::get_Password() {
return password_c;
}
void Configuration::set_Password(char* password ) {
strcpy(password_c, password);
}
String Configuration::get_ApiKeyValue() {
return apiKeyValue_c;
}
void Configuration::set_ApiKeyValue(char* apiKeyValue) {
strcpy(apiKeyValue_c, apiKeyValue);
}
bool Configuracao::loadFile() {
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
while(true);
}
StaticJsonDocument<700> doc;
File file = SPIFFS.open(("/config.json"), "r");
if (!file){
Serial.println("Failed to open file for reading");
//return;
}
DeserializationError error = deserializeJson(doc, file);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return -1;
}
strcpy(password_c, doc["password"]); // I belive that it can't work, but it work. password_c is private
strcpy(apiKeyValue_c, doc["apiKeyValue"]);
// - Test
Serial.println(get_Password()); //value ok!
Serial.println(password_c); //value ok!
file.close();
}
The commands work inside the method that reads the JSON file, but I thought this would not be possible since both members are private.
I can print the result of password_c and apiKeyValue_c right after strcpy().
Serial.println(get_Password()); // using the method
Serial.println(password_c); // direct (I don't know why this way works, as they are private.
I imagined that I would have to implement set methods to access these objects.
Can someone enlighten me?
Code that is outside of a class, and is not declared to be a
friendof that class, cannot access that class'sprivatemembers. But, code that in inside of the class's own methods can freely access the class'sprivatemembers. A class would be fairly useless if it couldn't access its own data.So, in this case, assuming you meant for
Configuracaoto beConfigurationinstead, and that you meant to declare aloadFile()method in theConfigurationclass, thenConfiguration::loadFile()can accessConfiguration's private members without restriction. But, any code that is using aConfigurationobject (and is not afriendofConfiguration) would not be able to access the private members at all, and would have to use its public getters/setters instead.