{"id":12416,"date":"2022-01-18T10:24:35","date_gmt":"2022-01-18T18:24:35","guid":{"rendered":"https:\/\/www.learncpp.com\/?p=12416"},"modified":"2024-09-16T16:15:13","modified_gmt":"2024-09-16T23:15:13","slug":"default-member-initialization","status":"publish","type":"post","link":"https:\/\/www.learncpp.com\/cpp-tutorial\/default-member-initialization\/","title":{"rendered":"13.9 &#8212; Default member initialization"},"content":{"rendered":"<p>When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition.  For members not marked as <code>static<\/code>, this process is sometimes called <strong>non-static member initialization<\/strong>.  The initialization value is called a <strong>default member initializer<\/strong>.<\/p>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Related content<\/p>\n<p>We cover static members and static member initialization in lesson <a href=\"https:\/\/www.learncpp.com\/cpp-tutorial\/static-member-variables\/\">15.6 -- Static member variables<\/a>.\n<\/p><\/div>\n<p>Here&#8217;s an example:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">struct Something\r\n{\r\n    int x;       \/\/ no initialization value (bad)\r\n    int y {};    \/\/ value-initialized by default\r\n    int z { 2 }; \/\/ explicit default value\r\n};\r\n\r\nint main()\r\n{\r\n    Something s1; \/\/ s1.x is uninitialized, s1.y is 0, and s1.z is 2\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>In the above definition of <code>Something<\/code>, <code>x<\/code> has no default value, <code>y<\/code> is value-initialized by default, and <code>z<\/code> has the default value <code>2<\/code>.  These default member initialization values will be used if the user doesn&#8217;t provide an explicit initialization value when instantiating an object of type <code>Something<\/code>.<\/p>\n<p>Our <code>s1<\/code> object doesn&#8217;t have an initializer, so the members of <code>s1<\/code> are initialized to their default values.  <code>s1.x<\/code> has no default initializer, so it remains uninitialized.  <code>s1.y<\/code> is value initialized by default, so it gets value <code>0<\/code>.  And <code>s1.z<\/code> is initialized with the value <code>2<\/code>.<\/p>\n<p>Note that even though we haven&#8217;t provided an explicit initializer for <code>s1.z<\/code>, it is initialized to a non-zero value because of the default member initializer provided.<\/p>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>Using default member initializers (or other mechanisms that we&#8217;ll cover later), structs and classes can self-initialize even when no explicit initializers are provided!\n<\/p><\/div>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For advanced readers<\/p>\n<p>CTAD (which we cover in lesson <a href=\"https:\/\/www.learncpp.com\/cpp-tutorial\/class-template-argument-deduction-ctad-and-deduction-guides\/\">13.14 -- Class template argument deduction (CTAD) and deduction guides<\/a>) cannot be used in non-static member initialization.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Explicit initialization values take precedence over default values<\/p>\n<p>Explicit values in a list initializer always take precedence over default member initialization values.<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">struct Something\r\n{\r\n    int x;       \/\/ no default initialization value (bad)\r\n    int y {};    \/\/ value-initialized by default\r\n    int z { 2 }; \/\/ explicit default value\r\n};\r\n\r\nint main()\r\n{\r\n    Something s2 { 5, 6, 7 }; \/\/ use explicit initializers for s2.x, s2.y, and s2.z (no default values are used)\r\n   \r\n    return 0;\r\n}<\/code><\/pre>\n<p>In the above case, <code>s2<\/code> has explicit initialization values for every member, so the default member initialization values are not used at all.  This means <code>s2.x<\/code>, <code>s2.y<\/code> and <code>s2.z<\/code> are initialized to the values <code>5<\/code>, <code>6<\/code>, and <code>7<\/code> respectively.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Missing initializers in an initializer list when default values exist<\/p>\n<p>In the previous lesson (<a href=\"https:\/\/www.learncpp.com\/cpp-tutorial\/struct-aggregate-initialization\/\">13.8 -- Struct aggregate initialization<\/a>) we noted that if an aggregate is initialized but the number of initialization values is fewer than the number of members, then all remaining members will be value-initialized.  However, if a default member initializer is provided for a given member, that default member initializer will be used instead.<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">struct Something\r\n{\r\n    int x;       \/\/ no default initialization value (bad)\r\n    int y {};    \/\/ value-initialized by default\r\n    int z { 2 }; \/\/ explicit default value\r\n};\r\n\r\nint main()\r\n{\r\n    Something s3 {}; \/\/ value initialize s3.x, use default values for s3.y and s3.z\r\n   \r\n    return 0;\r\n}<\/code><\/pre>\n<p>In the above case, <code>s3<\/code> is list initialized with an empty list, so all initializers are missing.  This means that a default member initializer will be used if it exists, and value initialization will occur otherwise.  Thus, <code>s3.x<\/code> (which has no default member initializer) is value initialized to <code>0<\/code>, <code>s3.y<\/code> is value initialized by default to <code>0<\/code>, and <code>s3.z<\/code> is defaulted to value <code>2<\/code>.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Recapping the initialization possibilities<\/p>\n<p>If an aggregate is defined with an initialization list:<\/p>\n<ul>\n<li>If an explicit initialization value exists, that explicit value is used.\n<\/li>\n<li>If an initializer is missing and a default member initializer exists, the default is used.\n<\/li>\n<li>If an initializer is missing and no default member initializer exists, value initialization occurs.\n<\/li>\n<\/ul>\n<p>If an aggregate is defined with no initialization list:<\/p>\n<ul>\n<li>If a default member initializer exists, the default is used.\n<\/li>\n<li>If no default member initializer exists, the member remains uninitialized.\n<\/li>\n<\/ul>\n<p>Members are always initialized in the order of declaration.<\/p>\n<p>The following example recaps all possibilities:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">struct Something\r\n{\r\n    int x;       \/\/ no default initialization value (bad)\r\n    int y {};    \/\/ value-initialized by default\r\n    int z { 2 }; \/\/ explicit default value\r\n};\r\n\r\nint main()\r\n{\r\n    Something s1;             \/\/ No initializer list: s1.x is uninitialized, s1.y and s1.z use defaults\r\n    Something s2 { 5, 6, 7 }; \/\/ Explicit initializers: s2.x, s2.y, and s2.z use explicit values (no default values are used)\r\n    Something s3 {};          \/\/ Missing initializers: s3.x is value initialized, s3.y and s3.z use defaults\r\n   \r\n    return 0;\r\n}<\/code><\/pre>\n<p>The case we want to watch out for is <code>s1.x<\/code>.  Because <code>s1<\/code> has no initializer list and <code>x<\/code> has no default member initializer, <code>s1.x<\/code> remains uninitialized (which is bad, since we should always initialize our variables).<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Always provide default values for your members<\/p>\n<p>To avoid the possibility of uninitialized members, simply ensure that each member has a default value (either an explicit default value, or an empty pair of braces).  That way, our members will be initialized with some value regardless of whether we provide an initializer list or not.<\/p>\n<p>Consider the following struct, which has all members defaulted:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">struct Fraction\r\n{\r\n\tint numerator { }; \/\/ we should use { 0 } here, but for the sake of example we'll use value initialization instead\r\n\tint denominator { 1 };\r\n};\r\n\r\nint main()\r\n{\r\n\tFraction f1;          \/\/ f1.numerator value initialized to 0, f1.denominator defaulted to 1\r\n\tFraction f2 {};       \/\/ f2.numerator value initialized to 0, f2.denominator defaulted to 1\r\n\tFraction f3 { 6 };    \/\/ f3.numerator initialized to 6, f3.denominator defaulted to 1\r\n\tFraction f4 { 5, 8 }; \/\/ f4.numerator initialized to 5, f4.denominator initialized to 8\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>In all cases, our members are initialized with values.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Provide a default value for all members.  This ensures that your members will be initialized even if the variable definition doesn&#8217;t include an initializer list.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Default initialization vs value initialization for aggregates<\/p>\n<p>Revisiting two lines from the above example:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">\tFraction f1;          \/\/ f1.numerator value initialized to 0, f1.denominator defaulted to 1\r\n\tFraction f2 {};       \/\/ f2.numerator value initialized to 0, f2.denominator defaulted to 1<\/code><\/pre>\n<p>You&#8217;ll note that <code>f1<\/code> is default initialized and <code>f2<\/code> is value initialized, yet the results are the same (<code>numerator<\/code> is initialized to <code>0<\/code> and <code>denominator<\/code> is initialized to <code>1<\/code>).  So which should we prefer?<\/p>\n<p>The value initialization case (<code>f2<\/code>) is safer, because it will ensure any members with no default values are value initialized (and although we should always provide default values for members, this protects against the case where one is missed).<\/p>\n<p>Preferring value initialization has one more benefit -- it&#8217;s consistent with how we initialize objects of other types.  Consistency helps prevent errors.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>For aggregates, prefer value initialization (with an empty braces initializer) to default initialization (with no braces).\n<\/p><\/div>\n<p>That said, it&#8217;s not uncommon for programmers to use default initialization instead of value initialization for class types.  This is partly for historic reasons (as value initialization wasn&#8217;t introduced until C++11), and partly because there is a particular case (for non-aggregates) where default initialization can be more efficient than value initialization (we cover this case in lesson <a href=\"https:\/\/www.learncpp.com\/cpp-tutorial\/default-constructors-and-default-arguments\/\">14.11 -- Default constructors and default arguments<\/a>).<\/p>\n<p>Therefore, we won&#8217;t be militant about enforcing use of value initialization for structs and classes in these tutorials, but we do strongly recommend it.<\/p>\n<div class=\"prevnext\"><div class=\"prevnext-inline\">\n\t<a class=\"nav-link\" href=\"https:\/\/www.learncpp.com\/cpp-tutorial\/passing-and-returning-structs\/\">\n <div class=\"nav-button nav-button-next\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Next lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">13.10<\/span>Passing and returning structs\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  \t<a class=\"nav-link\" href=\"\/\">\n  <div class=\"nav-button nav-button-index\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-home\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Back to table of contents<\/div>\n    <\/div>\n<\/div><\/a>\n  \t<a class=\"nav-link\" href=\"https:\/\/www.learncpp.com\/cpp-tutorial\/struct-aggregate-initialization\/\">\n  <div class=\"nav-button nav-button-prev\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-left\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Previous lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">13.8<\/span>Struct aggregate initialization\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  <\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. For members not marked as static, this process is sometimes called . The initialization value is called a . Related content We cover static members and &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/12416"}],"collection":[{"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/comments?post=12416"}],"version-history":[{"count":15,"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/12416\/revisions"}],"predecessor-version":[{"id":17612,"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/12416\/revisions\/17612"}],"wp:attachment":[{"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/media?parent=12416"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/categories?post=12416"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.learncpp.com\/wp-json\/wp\/v2\/tags?post=12416"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}