Home > Learning > Initialization lists in C++

Initialization lists in C++

New thing learned! This is actually a really nice one.

Suppose a class with three properties:

class MyClass
    MyClass(int property1, char property2, float property3);
    int m_property1;
    char m_property2;
    float m_property3;

A constructor that’s essentially trivial (no validation) would look like this:

MyClass::MyClass(int property1, char property2, float property3)
    m_property1 = property1;
    m_property2 = property2;
    m_property3 = property3;

There is, however, a more concise way to write this with something called an initializer list:

MyClass::MyClass(int property1, char property2, float property3)
: m_property1(property1), m_property2(property2), m_property3(property3)

Much cleaner. If some elements require validation, they don’t need to be in the list.

There’s a whole lot more here: http://www.cprogramming.com/tutorial/initialization-lists-c++.html

UPDATE (2012-02-09):

For this course I’m taking, I’m using GCC to compile. One of the differences I found with Visual Studio’s compiler is that with GCC requires that the elements initialized be listed in the same order as properties (in the class’ private section) and in the constructor.

UPDATE (2012-03-26)

One thing I had not caught on originally is beyond the syntax. Yes, it’s a clean syntax, but the main feature is that there is no pre-assignment. In C++, at the start of the constructor (in laymen’s terms, right after the opening bracket), all class attributes are assigned. What you’re doing with this:

m_property1 = property1;

is basically the second assignment of m_property1, the first being its default. If it’s a simple type, there’s no harm done, but if it’s an object of a class, that means the default constructor was called. Worst, if it’s a class you wrote, it means you have to give it a default constructor. If your class doesn’t naturally need a default constructor, this is bad. The extra instantiation alone, the hidden one, is bad, you’re wasting valuable resources. In an initialization list, the property is assigned directly. Waste not, want not.

Categories: Learning Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: