How can I initialize my private variable in my c++ class?
a.h:
class A {
private:
std::string& name;
public:
A(void);
~A(void);
bool load(std::string& name);
};
a.cpp:
#include <string>
#include "a.h"
A::A(void) {
this->name = "";
}
A::~A(void) {}
bool A::load(std::string& name) {
this->name = name;
}
The error:
a.cpp: In constructor ‘A::A()’:
a.cpp:3:1: error: uninitialized reference member in ‘std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}’ [-fpermissive]
A::A(void) {
^
In file included from a.cpp:2:0:
a.h:3:22: note: ‘std::__cxx11::string& A::name’ should be initialized
std::string& name;
I have initialized it in my constructor (in a.cpp), but it is still erroring.
nameto be astring&? Why no just astring? Making a class data member a reference is complicated stuff, because you cannot have it uninitialized to some actual string from the very beginning.