Initialising reference in constructor C++

Viewed 66630

I don't think is a duplicate question. There are similar ones but they're not helping me solve my problem.

According to this, the following is valid in C++:

class c {
public:
   int& i;
};

However, when I do this, I get the following error:

error: uninitialized reference member 'c::i'

How can I initialise successfully do i=0on construction?

Many thanks.

6 Answers

Reference should be initialised either by passing data to constructor or allocate memory from heap if you want to initialize in default constructor.

class Test  
{  
    private:
        int& val;  
        std::set<int>& _set;  
    public:  
        Test() : val (*(new int())),  
                _set(*(new std::set<int>())) {  }  

        Test(int &a, std::set<int>& sett) :  val(a), _set(sett) {  }  
};  

int main()  
{  
    cout << "Hello World!" << endl;  
    Test obj;  
    int a; std::set<int> sett;  
    Test obj1(a, sett);  
    return 0;  
}

Thanks

Related