iDevGames Forums
Question about Initialiser Lists - Printable Version

+- iDevGames Forums (
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Programming Languages & Scripting (/forum-8.html)
+--- Thread: Question about Initialiser Lists (/thread-2838.html)

Question about Initialiser Lists - anthony - Jan 11, 2008 08:35 AM


I've been looking through some C++ source code, other than that supplied on my programming course. I've seen a lot of constructors look like this:

MyClass(int i, double d):myInt(i), myDouble(d) {}

That's an initialiser list right? Is there an actual benefit to using them over writing your own set and get methods?
Or over using assignments in the constructor?

My background is predominantly as a Java programmer so get(), set() are more what I'm used to.

The only thing I can really think of is that by writing:

MyClass(int i, double d)
  myInt = i;
  myDouble = d;

it creates temporary variables and you also have to use each variables assignment operator.

I'd really appreciate an explanation if someone can give me one Smile



Question about Initialiser Lists - sohta - Jan 11, 2008 08:55 AM

Initializer lists are the only way to assign member const variables, Let's say you have a class like this:

class myWeirdVector
  myWeirdVector( unsigned int length )
  : mLength( length )
    mStorage = new float[ mLength ] ;

  float * mStorage ;
  const unsigned int mLength ;
} ;

The cool thing is that the mLength member variable gets initialized, and then it cannot be modified anymore.

It's also recommended to use initializer lists as much as possible because the compiler can generally optimize the assignment operation away by assigning values directly. See it like this: when allocating an object of the class, the memory gets set to the specified values instead of whatever was there (or zeroed out).

Question about Initialiser Lists - anthony - Jan 11, 2008 09:28 AM

Thanks sohta Smile

Question about Initialiser Lists - OneSadCookie - Jan 11, 2008 03:47 PM

Also: they have nothing to do with getters or setters...

Question about Initialiser Lists - sohta - Jan 11, 2008 05:24 PM

There is another, even more important use to these (I forgot to mention it because it's so obvious). When your class contains members that are classes, the initializer list allows you to control which constructor gets called for the member variable. If you do not list a class based member variable in your initializer list, the default constructor will be automatically used.

Question about Initialiser Lists - akb825 - Jan 11, 2008 07:54 PM

Also, the only way member variables that are references can be initialized is through the initializer list.