compile error about member variable initialization

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • George2

    compile error about member variable initialization

    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:
    #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<intvi;
    Foo foo = Foo (vi);
    
    
    return 0;
    }

    thanks in advance,
    George
  • Victor Bazarov

    #2
    Re: compile error about member variable initialization

    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


    Comment

    Working...