0

I need to save in Class static ref to a variable for use in nested classes in a future. I have no problem in use ref to a variable (not static), but with static i have to use int & myClass::refA = ... in someware. The problem is that i can use int & myClass::refA = ... only in myClass constuctor, because only there i got the ref for refA, in myClass mc(newA) colling. How to initialize a static reference to a variable inside the class constuctor?

Code:

class myClass
{
    private:
        static int & refA;
    public:
        myClass(int &_refA);
        void updateA();
};

myClass::myClass(int &_refA)
: refA(_refA)
{
}

void myClass::updateA() {
    refA = refA++;
}

int newA = 10;
myClass mc(newA);
mc.updateA(); 

Error:

In constructor 'myClass::myClass(int&)':

QF:17:3: error: 'int& myClass::refA' is a static data member; it can only be initialized at its definition

 : refA(_refA)
   ^

exit status 1
'int& myClass::refA' is a static data member; it can only be initialized at its definition
  • The question is why do you want to do this? The reason you can't is that references cannot be uninitialised so must be initialised when they are defined. – Alan Birtles Jul 13 '18 at 14:25
  • 1
    `static int* refA = nullptr;` and set it in constructor then ? – Jarod42 Jul 13 '18 at 14:27
  • 1
    What do you want to initialize it **to**? It is a static member, initializing it to (randomly) first argument to the constructor makes no sense. I sense XY problem. – SergeyA Jul 13 '18 at 14:31
  • I agree, it is a weird thing to do, seems like XY problem – Kai Guther Jul 13 '18 at 23:06

1 Answers1

1

You can hack this by using a static member function that has a local static variable which is set to the argument of the constructor when first called.

static int dummy =  1;

class myClass
{
private:
    static int &refA(int &in = dummy){
        static int &buf = in;
        return buf;
    };
public:
    myClass(int &_refA){refA(_refA);};
    void updateA();
};

The static function refA() now has a static member which will be initialized when the function is first called, which is when the first myClass is constructed. refA() now behaves like a static reference to the argument of the constructor of the first myClass object constructed.

Note that this is a horrible hack, if that is really the easiest solution to the underlying problem is another story (almost certainly not), and there might be very well a solution that does not require a static reference.

Kai Guther
  • 783
  • 3
  • 11