Question about Initialiser Lists

Member
Posts: 61
Joined: 2007.01
Post: #1
Hi,

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:

Code:
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:

Code:
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

Thanks,

Anthony
Quote this message in a reply
Member
Posts: 72
Joined: 2006.10
Post: #2
Initializer lists are the only way to assign member const variables, Let's say you have a class like this:

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

private:
  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).
Quote this message in a reply
Member
Posts: 61
Joined: 2007.01
Post: #3
Thanks sohta Smile
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #4
Also: they have nothing to do with getters or setters...
Quote this message in a reply
Member
Posts: 72
Joined: 2006.10
Post: #5
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.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #6
Also, the only way member variables that are references can be initialized is through the initializer list.
Quote this message in a reply
Post Reply