1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Copy Constructors

By David Bolton, About.com

2 of 10

Using Initializer Lists

Constructors can use an initializer list to pre-set values before the body of the constructor is entered. Here the phonerec class (from the previous page) is initialized with an initializer list.
phonerec() : name("Me"),phonenunber("555-1000") {}
An initializer can also call a function.
string getString() {
    return "value";
}

phonerec() : name(getString()),phonenunber("555-1000") {}
Use this with care as the order of execution of the initializer list is not the order of that that list but the order that members occur in the class. You should write the initializer list in the order that the members occur in the class, otherwise you risk using uninitialized member variables.

The example below shows the order that members are initialized. The initializer list is d, e, but the output is e d, exactly as the member variables are declared.

#include <iostream>

using namespace std;

int id() {
    cout << "d" << endl;
    return 1;
}
int ie() {
    cout << "e" << endl;
    return 1;
}

class a {
  public:

    int e;
    int d;
    
    a() : d(id()), e(ie()) { }
    
};

void main() {
    a A;
}

On the next page : Initializing an array

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Using Initializer Lists

©2009 About.com, a part of The New York Times Company.

All rights reserved.