Thread: Initializer lists, better or worse?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    An initializer list is required to initialize some variable types, e.g. references. Here is an example of how a reference type works:
    Code:
    #include<iostream>
    using namespace std;
    
    int main()
    {
    	int num1 = 10;
    	int num2 = 35;
    
    	int& rInt = num1;  //declare a reference variable and initialize it to num1
    	rInt += 10; 
    	cout<<num1<<endl; //20 (rInt is like a nickname for num1, so changing
                              //rInt changes num1.)
    
    	rInt = num2; //try to switch the reference to another variable
    	rInt += 4; //did rInt change num2? 
    	cout<<num2<<endl; //35(Nope!)
    	cout<<num1<<endl; //39 ??? (rInt is a synonym for num1, so rInt = num2 assigned
    	                  //num2 to num1, and rInt += 4 added 4 to num1.)
    	
    	return 0;
    }
    The result of all that is that you can't change what a reference refers to. rInt refers to num1 and that is all it will ever refer to, and doing something to rInt is the same as doing it to num1 directly. In order to set which variable a reference refers to, you have to initialize the reference variable when you declare it:
    Code:
    int& rInt = num1;
    If you don't initialize a reference variable when you declare it, the reference variable won't be able to refer to anything. Here is an example of that:
    Code:
    int age = 23;
    int& rAge;
    rAge = age; //error
    That is relevant to constructors and initializer lists because a constructor first constructs the object before it gets to the opening brace of the constructor body. Therefore, all the member variables have been created by that point, and a member variable that is a reference type will be created so that it doesn't refer to anything. That means in the constructor body it's too late to try and assign a variable name to the reference. On the other hand, using an initializer list causes the listed variables to be initialized with the specified values as they are created.
    Last edited by 7stud; 11-25-2005 at 09:18 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. error: braces around scalar initializer...
    By Osiris990 in forum C++ Programming
    Replies: 2
    Last Post: 02-27-2008, 03:22 PM
  2. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  3. Linked Lists 101
    By The Brain in forum C++ Programming
    Replies: 5
    Last Post: 07-24-2004, 04:32 PM
  4. Derived member variables in initializer lists
    By bennyandthejets in forum C++ Programming
    Replies: 13
    Last Post: 11-27-2003, 04:30 AM
  5. Initializer Lists
    By DISGUISED in forum C++ Programming
    Replies: 2
    Last Post: 01-18-2002, 06:12 PM