0

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.

1
  • 4
    Why do you need name to be a string&? Why no just a string? Making a class data member a reference is complicated stuff, because you cannot have it uninitialized to some actual string from the very beginning. Commented Dec 12, 2016 at 21:24

1 Answer 1

3

Let's fix the default constructor first: you cannot initialize references with an assignment. They need to be initialized with the initializer list:

static string empty_name("");

A::A(void) : name (empty_name) {  
}

Note the use of empty_name variable, scoped to translation unit. This lets you initialize a reference member to some object.

As far as the load member function goes, there is no way to re-assign a reference after it has been created. If you need this functionality, your best bet is to replace a reference with either a pointer if you need to access an external std::string object, or a copy (i.e. std::string name) if you do not need to reference a string that is external to your object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.