Click to See Complete Forum and Search --> : Reference Variable As Class Member


aruzinsky
September 9th, 2002, 05:15 PM
How do I initialize a reference variable declared inside a class or struct? I need a simple code example.

jfaust
September 9th, 2002, 05:42 PM
Use the constructor initializer list:


class A
{
public:
A(int& ref)
: m_ref(ref)
{
}

private:
int& ref;
};


Jeff

aruzinsky
September 9th, 2002, 09:36 PM
Thank you. I am ashamed to admit that I have never seen this before.

jfaust
September 9th, 2002, 10:18 PM
It really doesn't happen that often. Now you must guarantee that the lifetime of the passed-in parameter is at least as long as the class instance. It's usually not worth the trouble. At least with a pointer, it can be set to NULL.

I actually had to compile this example to ensure myself this was how it really works. So, no reason to be ashamed ;)

Jeff