egor_hm egor_hm - 6 months ago 43
C++ Question

Initialize member references correctly

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

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


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; }

        int* x_;
        int* y_;

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


    return 0;