CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Threaded View

  1. #1
    Join Date
    Mar 2010
    Posts
    71

    Help - how to initialize reference variable?

    Hi,

    This is an urgent issue so your help would be highly appreciated.

    The following code is extracted from a real project.

    Code:
    #include <iostream>
    using namespace std;
    
    class B
    {
      public:
        B(const int &n) : i(n)
        {
          cout << "In B constructor" << endl;
        }
    
      private:
        int &i;
    };
    
    int main()
    {
      int i = 28;
      B b(i);
    
      return 0;
    }
    In this code snap, B::i must be a reference and B's constructor must take "const int &n". When building this code, I got compile error:

    const_constructor.cpp: In constructor 'B::B(const int&)':
    const_constructor.cpp:8: error: invalid initialization of reference of type 'int&' from expression of type 'const int'

    Could someone please tell me how I fix this compile error?

    Thanks,
    BJT
    Last edited by BJT; September 15th, 2010 at 10:21 AM.

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