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:
    #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. Advertising

  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. Advertising

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.

Share This Page