Initializer Lists

This is a discussion on Initializer Lists within the C++ Programming forums, part of the General Programming Boards category; what is the advantage(s) of using an initializer list such as.... construct() : var1(0), var2(0) { } instead of ....... ...

  1. #1
    Still A Registered User DISGUISED's Avatar
    Join Date
    Aug 2001
    Posts
    499

    Initializer Lists

    what is the advantage(s) of using an initializer list such as....

    construct() : var1(0), var2(0) { }

    instead of .......

    construct() { var1 = 0; var2 = 0; }

    The book I am reading says to always use the list because it's better, but doesn't tell me why.

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    When you create an instance of a class each member object that it contains will be constructed before the body of the instance constructor is called (the constructor body is only executed when the allocation for all the members of the class has been done in full). So, if you have user-defined objects within your class, then their default constructors will be called initially and then when the body of the constructor of the 'outer' class is executed any initialisation of these 'inner' classes will be done using copy or conversion constructors. If you don't use an initialisation list then you'll get two constructors called for the member objects.

    The use of initialisation lists gets around this by passing the initialisers to the member objects for use in their initial creation.

  3. #3
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Small, but important, correction. The constructor for any object is only called once.

    If you don't initialize an object in the initalizer list, its default constructor will get called. When you then "initialize" it again in the function body, simply are using the assignment operator =.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

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. Initializer lists, better or worse?
    By Ganoosh in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2005, 10:01 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 11:03 AM
  4. Linked Lists 101
    By The Brain in forum C++ Programming
    Replies: 5
    Last Post: 07-24-2004, 05:32 PM
  5. Derived member variables in initializer lists
    By bennyandthejets in forum C++ Programming
    Replies: 13
    Last Post: 11-27-2003, 04:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21