How do I initialize a reference variable declared inside a class or struct? I need a simple code example.
Printable View
How do I initialize a reference variable declared inside a class or struct? I need a simple code example.
Use the constructor initializer list:
JeffCode:class A
{
public:
A(int& ref)
: m_ref(ref)
{
}
private:
int& ref;
};
Thank you. I am ashamed to admit that I have never seen this before.
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