-1

I have float variable witch its initial value is passed to function as reference.
I need to set this reference value to struct that holds data.
There is some work that is done and I need to get the updated value back.
Here is the flow in pseudo code:

class Foo
{
   float initVal = 20;
   GUImanager gUImanager;
   gUImanager.SetVariableValue(initVal);

   // the initVal float varibal should updated from
   // GUImanager class with the new values here .

};





 struct dataHolder
    {
      dataHolder(float& _floatref)
     {
// here i get the compilation error :
//error C2758: 'dataHolder::floatHolder' : a member of reference type must be initialized
        floatHolder = _floatref;
     }
     float& floatHolder;
    };

    class GUImanager
    {
    public:
          void GUImanager::SetVariableValue(float const&  _floatRef)
          {
              dataHolder* pdataHolder = new pdataHolder(_floatRef);
          } 
         float i = 0.0f;

         while(true)
         {
             pdataHolder.floatHolder+ = i++;
         }
    }

I was reading some answers that are dealing with this subject but haven't found any answer that helps me with my problem. How can I set the reference with something that the compiler will pass the compilation?

BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70
user63898
  • 29,839
  • 85
  • 272
  • 514
  • 1
    Define the constructor as `dataHolder(float& _floatref): floatHolder(_floatref) {}`, references cannot be assigned to, they must be initialized. Or don't define a constructor at all and use the class as an aggregate. – user657267 Dec 04 '15 at 08:56

1 Answers1

2

A reference must be initialised, and the place to initialise members is the initialiser list:

dataHolder(float& _floatref) : floatHolder(_floatref)
{
}

Your constructor contains an assignment, and the assignment will assign a value to the object that the reference refers to (and it's not referring to anything unless you initialise it).

molbdnilo
  • 64,751
  • 3
  • 43
  • 82