0

I have the following code:

#include<iostream>
using namespace std;

class Vec{
    private:
        int& var;
    public:
        Vec(int& tmp){
            var = tmp;
        }
};
int main(){
    int x = 10;
    Vec v1(x);
}

but it gives a compilation error:error: uninitialized reference member in ‘int&’ [-fpermissive]

How to resolve this?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

1 Answers1

5

You should use an initializer list.

#include<iostream>
using namespace std;

class Vec{
    private:
        int& var;
    public:
        Vec(int& tmp) : var(tmp) {}
};
int main(){
    int x = 10;
    Vec v1(x);
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • i am not sure what an initializer list means! can someone explain this or point to some good resource? Thanks in advance! –  Jul 13 '22 at 18:38
  • @AJ: Do you know the difference between initialization and assignment? – Ben Voigt Jul 13 '22 at 18:42