egor_hm egor_hm - 1 year ago 74
C++ Question

Initialize member references correctly

class Temp {
public :
Temp(X& x): x_(x) {}
Temp(X& x, Y& y) : x_(x), y_(y) {}
...
private:
X& x_;
Y& y_;
}


I got the error because in case of
Temp(X& x): x_(x)
the reference
y_
is not initialized. What is the common practice to write such a class correctly ?

Answer Source

I will suggest another approach, even though that may be not what you are looking for.

It doesn't use reference variables (memory pointers instead), it also doesn't use boost, but it will allow you to keep both constructors without spending any more memory resources.

#include <iostream>

class Temp
{
    public :
        Temp(int& x): x_(&x), y_(NULL) {}
        Temp(int& x, int& y) : x_(&x), y_(&y) {}
        void print() { std::cout << "*x_: " << *x_ << std::endl; }

    private:
        int* x_;
        int* y_;
};

int main()
{
    int x = 5;
    Temp tmp(x);

    tmp.print();

    return 0;
}