CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2002
    Posts
    173

    Reference Variable As Class Member

    How do I initialize a reference variable declared inside a class or struct? I need a simple code example.

  2. #2
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    Use the constructor initializer list:

    Code:
    class A
    {
    public:
    	A(int& ref)
    	: m_ref(ref)
    	{
    	}
    
    private:
    	int& ref;
    };
    Jeff

  3. #3
    Join Date
    Sep 2002
    Posts
    173
    Thank you. I am ashamed to admit that I have never seen this before.

  4. #4
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured