compile error about member variable initialization

Discussion in 'C++' started by George2, Dec 4, 2007.

  1. George2

    George2 Guest

    Hello everyone,


    Why the below code segment will result in compile error? When I change
    code to the comment one (constructor), it can compile. The compiler is
    too stupid? :)

    I am using Visual Studio 2005.

    --------------------
    main.cpp(13) : error C2758: 'Foo::vi' : must be initialized in
    constructor base/member initializer list

    see declaration of 'Foo::vi'
    --------------------

    Code (Text):

    #include <vector>

    using namespace std;

    class Foo {

    private:

        vector<int>& vi;

    public:

        Foo (vector<int>& vi_in)
        {
            vi = vi_in;
        }
    /*
        Foo (vector<int>& vi_in) : vi (vi_in)
        {
        }
    */
    };

    int main()
    {
        vector<int> vi;
        Foo foo = Foo (vi);


        return 0;
    }
     

    thanks in advance,
    George
     
    George2, Dec 4, 2007
    #1
    1. Advertisements

  2. George2 wrote:
    > Why the below code segment will result in compile error? When I change
    > code to the comment one (constructor), it can compile. The compiler is
    > too stupid? :)
    >
    > I am using Visual Studio 2005.
    >
    > --------------------
    > main.cpp(13) : error C2758: 'Foo::vi' : must be initialized in
    > constructor base/member initializer list
    > [..]


    No, the compiler is not too stupid. References have to be initialised.
    The only place where reference members can be initialised is the c-tor
    initialiser list.

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask
     
    Victor Bazarov, Dec 4, 2007
    #2
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    961
    Peter_Julian
    Oct 10, 2005
  2. Randy
    Replies:
    5
    Views:
    412
    JustBoo
    Jan 13, 2006
  3. Nagaraj
    Replies:
    1
    Views:
    1,053
    Lionel B
    Mar 1, 2007
  4. Angus
    Replies:
    1
    Views:
    2,819
  5. aaragon
    Replies:
    2
    Views:
    705
    James Kanze
    Nov 2, 2008
Loading...

Share This Page