C++ 2011: Uniform Initialization

In C++, initializing objects is not done in the same manner in all contexts. The rules for initialization and constructors are not really simple and developers sometimes have to write lot of explicit code for initializing objects. Fortunately the new C++ standard comes to the rescue, offering a uniform initialization syntax and semantics.

The way it was before C++ 2011

Let's take the following structure as a start point.

struct Color
{
    unsigned char A;
    unsigned char R;
    unsigned char G;
    unsigned char B;
};

If you want to initialize an object of this type, then you can write:

Color c;
c.A = 0xff;
c.R = 0xff;
c.G = 0x00;
c.B = 0x00;

But there is a simpler way to write that:

Color c = {0xff, 0xff, 0x00, 0x00};

If you want to zero the entire structure, then you can write:

Color c = {0};

However, you cannot use this initialization type to initialize all the members with 0xff, for instance. If you write

Color c = {0xff};

then only A will be 0xff, the other fields would be initialized with a default value, which is 0.

Since this is a POD (Plain Old Data) type (which is a scalar or a POD class - a class with no user defined constructors or destructor, no user defined copy assignment operator, no base classes or virtual functions, no private or protected non-static data and no static data that is non-POD types) you could also write:

memset(&c, 0, sizeof(c));

Mind you, initializing with 0 with memset works for any POD type, however, initializing with another value, say 1, will not have the expected result; if A, R, G and B would have been ints for instance, because memset puts the specified value in every byte starting at the specified address for the specified count, you'd get ints that are 0x01010101 instead of simply 1.

When it comes to array you can initialize all the elements of the array with 0 as in:

Color ca[2] = {0};

which is identical to

Color ca[2] = {{0}, {0}};

However, if you want to initialize with something other than 0, then you can write:

Color ca[2] = {{0}, {0xff, 0xff, 0x00, 0x00}};

Now, another way to initialize Color would be to define a constructor (which makes the type non-POD, so no more memset). The default value of the constructor parameters allow you to declare arrays of this object. Otherwise, since there is no default constructor, it wouldn't be possible to declare an array of Color.

struct Color
{
    unsigned char A;
    unsigned char R;
    unsigned char G;
    unsigned char B;
 
    Color(
       unsigned char a = 0, 
       unsigned char r = 0,
       unsigned char g = 0,
       unsigned char b = 0): A(a), R(r), G(g), B(b)
    {}
};

In this case you can say:

Color c(0xff, 0xff, 0x00, 0x00);

However, since Color is no longer an aggregate (because it has a user defined constructor) this initialization is no longer supported; the following issues errors:

Color c = {0xff, 0xff, 0x00, 0x00};

Color ca[2] = {{0}, {0xff, 0xff, 0x00, 0x00}};

If instead of using an array, we'd want to use a vector of Color, then initializing it would be only possible like this:

vector<Color> cv;
cv.push_back(Color(0));
cv.push_back(Color(0xff, 0xff, 0x00, 0x00));

Or

vector<Color> ca(2);
ca[1] = Color(0xff, 0xff, 0x00, 0x00);

Or

ca[1].A = 0xff;
ca[1].R = 0xff;
ca[1].G = 0x00;
ca[1].B = 0x00;

Or if you'd have an array of Color, then you can say:

Color ca[2] = {Color(0), Color(0xff, 0xff, 0x00, 0x00)};
vector<Color> cv(ca, ca+2);

Enter C++ 2011

The new standard introduces a new way of initializing objects, in a more uniform manner. Even though Color is a non-POD type you can write:

Color c {0xff, 0xff, 0x00, 0x00};

Color ca[2] {{0}, {0xff, 0xff, 0x00, 0x00}};

vector<Color> ca {{0}, {0xff, 0xff, 0x00, 0x00}};

Or (these two being identical)

Color c = {0xff, 0xff, 0x00, 0x00};

Color ca[2] = {{0}, {0xff, 0xff, 0x00, 0x00}};

vector<Color> ca = {{0}, {0xff, 0xff, 0x00, 0x00}};

Or with a map:

map<string, Color> colors = {
  {"red",     {0xff, 0xff, 0x00, 0x00}},
  {"green",   {0xff, 0x00, 0xff, 0x00}},
  {"blue",    {0xff, 0x00, 0x00, 0xff}},
};

It is important to note that the initialization with the parenthesis, as shown in the previous paragraph as the only way to initialize non-POD types before C++ 2011, is still available.

Also note that in the following code sample, the first vector will have three elements (initialized with the default value), while the second will have a single element with value 3.

vector vec1(3);
vector vec2{3};

If the array or the vector were members of a class, the following initialization could be done:

class foo
{
   int data[3];
public:
   foo(): data{1,2,3} {}
};

class bar
{
   vector data;
public:
   bar(): data{1,2,3} {}
};

What if the array would be dynamically allocated on the heap? Then, you can use the same initialization syntax with {}:

int* data = new int[3] {1,2,3};

Or, in case it is part of a class

class foobar
{
   int* data;
public:
   foobar(): data(new int[3]{1,2,3}){}
};

It is also possible to use the curly braces to initialize an object in a return statement:

Color make_color(unsigned char r, unsigned char g, unsigned char b)
{
   return {0xff, r, g, b};
}

Or for a function call:

void use_color(Color c)
{
}

use_color({0xff, 0xff, 0x00, 0x00});

Conclusions

The new C++ standard brings a new, uniform initialization syntax and semantics, helping developers to write simpler and uniform code. Using the curly braces {} constructs the same value in all contexts where it is legal. Unfortunately, not all compilers support this new feature at the time of writing this article, but they will pretty soon.



About the Author

Marius Bancila

Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for a Norwegian-based company. He is mainly focused on building desktop applications with MFC and VC#. He keeps a blog at www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++/VC++ programmers.

Related Articles

Comments

  • Beats musik komme til dig af Dr. Dre

    Posted by wmtcce244 on 07/17/2013 12:57am

    Uanset om du har brug for netværks personlig brug derhjemme, eller hvis du har brug for at udstyre dit barns skole, som er en meget sød, med henblik på at få en favorit Beats hovedtelefoner nysgerrig, jeg gravede lidt dybere, og jeg gotta jeg ser frem til i alle de basale behov klik her. Faktisk ønsker jeg dig til at bryde det ned til den korte form.Da jeg fik den elskede monster beats hovedtelefoner, og jeg føler meget glad og spændt, men hvad er den virkelige god pleje af det, selv om de nye hovedtelefoner altid vil indtage markedet hurtigt, men når jeg har beats er stadig som ny, tilfredshed aldrig forladt. Vi taler om nogle enkle opførsel om forlængelse af levetiden for headsettet [url=http://beatsbydrdredanmark.bloguedobebe.com/]beats by dre[/url] Så hvorfor kan meget vel blive set alle omkring dig Beats hovedtelefoner? Dette er helt sikkert helt en god måde Dre headset sammen med lyd annullerer headsets BIDRAGET er bare ikke headsets hypotese. Enhver sang på dette tidspunkt har jeg vokset til at være en god must, mange inden for den nødvendige. tage et godt udseende med alle gode? Song overlegen tone overstrømmende på dine vegne, i din lethed, ingen tvivl om du kender overlegen sang indgivet til din mobiltelefon eller blot film battler. [url=http://beatsbydrdredanmark.weebly.com/]beats by dre[/url] Medmindre selvfølgelig, at du hellere træt, du aldrig kommer i seng, headsets i tillæg til et program, ferie kontorstol, nikkende, venter på dine vegne. Uanset om du er under metroen, workout, til hjemmet, hvor du arbejder af anden vej, for eksempel, giver næsten de fleste mennesker et headset hver eneste dag. Men når du burde “dele” enhver sang alle lytte, vil du have en persons Beats det alle.

    Reply
  • Fake Oakley Romeo sale online

    Posted by dixxdsnqe on 06/26/2013 06:30pm

    Cheap oAkLey sunglasses ,Oakley sunglasses for any class itself, it's got confirmed to be a true fashion craze, and have found their way into some well-known Hollywood film. She wore beautiful, she is not the only one. When people are searching for (celebrities), to determine what the latest trends, they wear has become a support and recognition. Replica Oakley Sunglasses ,All lens offers truer color perception in sunny the weather is good purpose, three points suitable to keep the lens precise optical alignment of comfort and gratifaction. Inside a completely independent laboratory, Oakley, Sunglasses metallurgist by using 425,000 plasma bolt shape, an ultra-lightweight titanium alloy metal tiles, fully integrated science and art of design. cheap Oakley HIjInx ,It's also harmful UV of the human eye is completely blocked, to ensure people in bright light, as soon as your long-term activities, and eye fatigue, vision more clearly the three-dimensional, and also to protect. The structure inspiration for Oakley, Oakley LIVESTRONG exclusive edition sunglasses from U.S. Major League Baseball official glasses to assist you make your mind more mysterious. When choosing sunglasses, sunglasses you might like to know fits into your budget, what exactly is the eyes, you are properly safeguarded. You possibly can select a black frame, gold, guns, brown or ivory. Flexible flexible frame from what you possibly can sustain your ears behind the lens and linked to the framework resized. Long-term experience, ultraviolet radiation also can produce cataracts, rapid express our eye damage, when the UV radiation power is sufficient vision from contact lens opacities. Oakley is worth it off said and done, the people's lifestyle, sports or polarized sunglasses will find the proper product manufacturers with this. Oakley will be able to meet your entire requirements, and exceed an original imagination and creativity and also the target, so your joy outside, with surprise. Oakley interchangeable lens technology, created to assist you maintain changing light conditions, to improve the performance in different environment. Oakley sunglasses (female) advantages from its special history, the majority them seeking to imitate them. Few women simply pick-up the glasses, they find what they really want. The pilot sunglasses is amongst the most favored nowadays in males business women styles. Oakley sunglasses, a model of this style, the standard brown shadows, they could almost match any equipment.

    Reply
  • It's been a rechannel week quest of swift snitch call|hole egress online

    Posted by Stoompota on 06/26/2013 10:10am

    Rising Tide Fair Trade creates [url=http://andysdm.com/]coach [url=http://andysdm.com/]coach outlet for sale[/url] outlet online store[/url] handbags from brilliantly colored vintage saris and cruelty [url=http://andysdm.com/]coach outlet website[/url] free suede trim.The textiles for each bag are individually chosen. The bags come in [url=http://andysdm.com/]coach outlet[/url] an elaborate range of colors and fabrications to choose from. Each bag is a one-of-a-kind original.

    Reply
  • 2013 the submit to and horseplay goods online on mankind, Hire a nosedive more you products onw

    Posted by Glonesciece on 06/25/2013 11:36am

    Check out the Disco [url=http://www.reelia.co.uk/]karen millen online[/url] Rainbow Jai Bright on AngelJackson.com (all images courtesy of Angel Jackson) Check out more bags by Angel Jackson on Handbago.com! Gossip Girl loves Angel Jackson! Young British accessories label, Angel Jackson is known for it's unique and modern [url=http://www.reelia.co.uk/]karen millen online[/url] accessories! This renowned fashion label has been recognized by the British Fashion Council, [url=http://www.reelia.co.uk/]karen millen dresses online[/url] British Vogue, and the esteemed Designer Fashion Fund. Angel Jackson bags are elegant, extravagant, and have a "don't [url=http://www.reelia.co.uk/]http://www.reelia.co.uk/[/url] mess with me" chic-ness. Angel Jackson deconstructs ideas to produce accessories that are both modern and super chic. This brand is a favorite of daughters of rock n' roll legends and glamourous Gossip Girls! Blake Lively is a personal fan of Angel Jackson bags. Take a cue from this Gossip Girl and check them out!!

    Reply
  • lwrdohezb

    Posted by Allonnanvam on 06/18/2013 12:50pm

    URARA(ウララ)モデルが穿いているスカートはこちらからどうぞモデルの身長は155です MCM バッグ mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 URARA(ウララ)のコートです。生地はコートとしては厚くなく薄くなく、伸縮性はなく、前の6つボタンを外して着用します。(内側はクルミボタンになります)ワッシャー仕上げとなります。 「今回の震災で被害に遭われた方々に、心よりお悔やみとお見舞いを申し上げます。『こどもの未来』は東日本大震災によって被災された多くの方々へ、少しでもお力になれればと考えて作ったものです。海洋ミネラルMCM(マリーナ・クリスタル・ミネラル)と真コンブを使用したサプリメントで、少しでも被災地の子どもたちが元気になれば幸いです。 」と言うもの。健康生活の継続のため、テロメリンは栄養素のバランスにこだわっています。注目のレスベラトロールをはじめとするポリフェノールに着目し、さらに葉酸、セレンなど健康な生活の維持に不可欠といわれる成分をプラスした栄養補助食品です。 こちらの常連さんがよく言われるのが「気遣いが嬉しい店だ」ということです。このメニューを見ると、その理由の一端が見えます右側のトッピングメニューに注目してください。「味玉半分」や「ワンタン3コ」「チャーシュー2枚」など、一般のラーメン店ではほとんど見ない、ちょっとトッピングメニューが並んでいるのが分かるでしょうか通常のトッピングでは「ちょっと多いなぁ」と思う女性や、「もう少し食べたいけど、高くなるし・・・」というお客様には嬉しいのではないでしょうか。

    Reply
  • Planchas GHD Midnight Deluxe Gift Set es el mejor regalo para sus amantes o amigos

    Posted by hanmeihm on 05/30/2013 04:44pm

    [url=http://www.comprarsaleghd.webstarts.com/]planchas ghd baratas[/url] Imagina que estoy tentado a ofrecerme, pero el precio de € 245 puede ser un poco de freno a comprar ... Al mismo tiempo, la innovacin tecnolgica puede ser interesante si suavizar el cabello regularmente. Respeta el cabello se calienta en 20 segundo y tiene un control total de la temperaturaS, se vende un poco de sue?o, pero queremos creer, al menos yo (creo). [url=http://www.planchasespanaghdtop.net/plancha-pelo-ghd/]ghd baratas[/url] Con varias nuevas caractersticas funcionales de las planchas de pelo GHD y planchas son simplemente magnfico para el estilo de su cabello. De las celebridades a la chica de al lado de los alisadores de pelo GHD son el gran favorito de todas las personas conscientes de la moda. [url=http://www.planchasespanaghdtop.net/]GHD Plancha España[/url] La primera straightner ghd era b¢sicamente aos antes de la competitividad ltimos dos mil. Planchas para el pelo durante ese tiempo el peso placas de aluminio muy ligeros y un montn de sauna elegido como medida para encontrar la mejor apariencia. La clave en la parte trasera de la m¢s alta eficacia de su ghd era b¢sicamente la derecha abajo a varios elementos principales.

    Reply
  • cheap sunglasses online

    Posted by mgliliImpumpidx on 03/29/2013 10:14am

    http://fakeGucciwayfarer.webs.com - fake ray ban wayfarer fake ray ban wayfarer http://wholesalesunglasseschic.webs.com - wholesale oakley sunglasses discount oakleys http://akeoakleysunglasses.webs.com - fake ray ban sunglasses fake ray ban http://fakeguccisunglasses.webs.com - fake oakley sunglasses oakley discount http://fakeGucciwayfarer.webs.com - fake ray ban discount ray ban sunglasses

    Reply
  • http://www.oakleysunglassesoutc.com/ mwifxw

    Posted by http://www.oakleysunglassesoutc.com/ Mandybkq on 03/29/2013 05:43am

    Tan Yan personally about things. Cao Kun is again reluctant must obey orders, just like flesh general Te Wulian personally sent to the Hunchun temporary training camp, where to get the necessary information from Vladivostok Zhaoheng Jun will personally training ghd. The action to the highest decision-making is Zhaoheng Jun, in order to compensate for the lack of ghd straightener, Army Staff also deployed special an experience is also highly Zhao Hengjun training Colonel General Staff from Beijing to Hunchun assist ghd sale. Zhao Hengjun and the intersection of the army is not much, but ghd hair straightener owned network of people was staggering, when cheap ghd practiced the soldiers Yazi are at least colonel, Hunchun Lijun Han Songbing policies come from the same ghd sects. In the Tan Yan Training Te Wulian when, Zhaoheng Jun few appearances, but for Te Wulian soldiers.

    Reply
  • hats wholesale

    Posted by xxds1dq on 03/28/2013 11:59pm

    [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping f ifkn [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale j wyay[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats q znwr[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats h iees[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps i zrrn[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale e lhcg [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps b aveb [url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies x wyiv[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale n zijh[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale q dkya[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap z mkjs[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping n yqlo [url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks y mvpa [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale q cdfo[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online x nglj[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap k pxwa[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks w ogga[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale e wljf

    Reply
  • fitted hats wholesale

    Posted by xxds7lf on 03/28/2013 10:08am

    [url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale j gbjw [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale t hcxt[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale i wuob[url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps v hdoj[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping q dnrt[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats j bvqc [url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats y gjzl [url=http://wholesalefittedhat.webs.com]fitted hats wholesale[/url] fitted hats wholesale u ptzd[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats l wnqd[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks d tgbx[url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online d pxws[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap w ltcd [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale z kivn [url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks e idcw[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale c mdoy[url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap l lgrg[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks d kjbd[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats b tjsp

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • This paper introduces IBM Java on the IBM PowerLinux 7R2 server and describes IBM's implementation of the Java platform, which includes IBM's Java Virtual Machine and development toolkit.

  • Agile methodologies give development and test teams the ability to build software at a faster rate than ever before. Combining DevOps with hybrid cloud architectures give teams not just the principles, but also the technology necessary to achieve their goals. By combining hybrid cloud and DevOps: IT departments maintain control, visibility, and security Dev/test teams remain agile and collaborative Organizational barriers are broken down Innovation and automation can thrive Download this white paper to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds