{"id":5314,"date":"2017-09-08T19:46:36","date_gmt":"2017-09-08T19:46:36","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-constructors\/"},"modified":"2023-06-26T12:07:00","modified_gmt":"2023-06-26T12:07:00","slug":"c-core-guidelines-constructors","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-constructors\/","title":{"rendered":"C++ Core Guidelines: Constructors"},"content":{"rendered":"<p>The lifecycle of each object starts with its creation; therefore, this post will be about the thirteen most fundamental rules for objects: constructor rules.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p>Twelve rules are too many for one post. Therefore, I will cover only the first eleven. Why not just ten rules? Because the eleventh rule is just too attractive. The remaining two are part of the next post. Here are the thirteen rules.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignright size-full wp-image-5311\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280.png\" alt=\"stork 1324371 1280\" width=\"400\" height=\"323\" style=\"float: right;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280.png 1280w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280-300x243.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280-1024x828.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280-768x621.png 768w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Constructor_rules\"><\/span>Constructor rules:<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<ul>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-ctor\">C.40: Define a constructor if a class has an invariant<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-complete\">C.41: A constructor should create a fully initialized object<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-throw\">C.42: If a constructor cannot construct a valid object, throw an exception<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-default0\">C.43: Ensure that a value type class has a default constructor<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-default00\">C.44: Prefer default constructors to be simple and non-throwing<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-default\">C.45: Don\u2019t define a default constructor that only initializes data members; use member initializers instead<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-explicit\">C.46: By default, declare single-argument constructors <code class=\"highlighter-rouge no-highlight\">explicit<\/code><\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-order\">C.47: Define and initialize member variables in the order of member declaration<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-in-class-initializer\">C.48: Prefer in-class initializers to member initializers in constructors for constant initializers<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-initialize\">C.49: Prefer initialization to assignment in constructors<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-factory\">C.50: Use a factory function if you need \u201cvirtual behavior\u201d during initialization<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-delegating\">C.51: Use delegating constructors to represent common actions for all constructors of a class<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-inheriting\">C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization<\/a><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>So, let&#8217;s look at the rules in detail. For further analysis, use the links to the rules.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C40_Define_a_constructor_if_a_class_has_an_invariant\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-ctor\">C.40: Define a constructor if a class has an invariant<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>An invariant of an object is a characteristic of the object that should hold for its entire lifetime. The place to establish such an invariant is the constructor. An invariant can be a valid date.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Date<\/span> {  <span style=\"color: #0099ff; font-style: italic;\">\/\/ a Date represents a valid date<\/span>\r\n              <span style=\"color: #0099ff; font-style: italic;\">\/\/ in the January 1, 1900 to December 31, 2100 range<\/span>\r\n    Date(<span style=\"color: #007788; font-weight: bold;\">int<\/span> dd, <span style=\"color: #007788; font-weight: bold;\">int<\/span> mm, <span style=\"color: #007788; font-weight: bold;\">int<\/span> yy)\r\n        <span style=\"color: #555555;\">:<\/span>d{dd}, m{mm}, y{yy}\r\n    {\r\n        <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #555555;\">!<\/span>is_valid(d, m, y)) <span style=\"color: #006699; font-weight: bold;\">throw<\/span> Bad_date{};  <span style=\"color: #0099ff; font-style: italic;\">\/\/ enforce invariant<\/span>\r\n    }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n<span style=\"color: #9999ff;\">private:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> d, m, y;\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C41_A_constructor_should_create_a_fully_initialized_object\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-complete\">C.41: A constructor should create a fully initialized object<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>This rule is quite similar to the previous one. Accordingly, creating the fully initialized object is the job of the constructor. A class having an <span style=\"font-family: courier new,courier;\">init<\/span> method is asking for trouble.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X1<\/span> {\r\n    <span style=\"color: #007788; font-weight: bold;\">FILE<\/span><span style=\"color: #555555;\">*<\/span> f;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ call init() before any other function<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    X1() {}\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> init();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ initialize f<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">read<\/span>();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ read from f<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>()\r\n{\r\n    X1 file;\r\n    file.read();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ crash or bad read!<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    file.init();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ too late<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The user might mistakenly invoke <span style=\"font-family: courier new,courier;\">read<\/span> before <span style=\"font-family: courier new,courier;\">init <\/span>or might forget to invoke <span style=\"font-family: courier new,courier;\">init.<br \/><\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"C42_If_a_constructor_cannot_construct_a_valid_object_throw_an_exception\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-throw\">C.42: If a constructor cannot construct a valid object, throw an exception<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Accordingly to the previous rule: throw an exception if you can not construct a valid object. There is not much to add. If you work with an invalid object, you must check its state before its usage. This is highly error-prone. Here is an example from the guidelines:<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X3<\/span> {     <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: the constructor leaves a non-valid object behind<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">FILE<\/span><span style=\"color: #555555;\">*<\/span> f;  \r\n    <span style=\"color: #007788; font-weight: bold;\">bool<\/span> valid;\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    X3(<span style=\"color: #006699; font-weight: bold;\">const<\/span> string<span style=\"color: #555555;\">&amp;<\/span> name)\r\n        <span style=\"color: #555555;\">:<\/span>f{fopen(name.c_str(), <span style=\"color: #cc3300;\">\"r\"<\/span>)}, valid{<span style=\"color: #336666;\">false<\/span>}\r\n    {\r\n        <span style=\"color: #006699; font-weight: bold;\">if<\/span> (f) valid <span style=\"color: #555555;\">=<\/span> <span style=\"color: #336666;\">true<\/span>;\r\n        <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    }\r\n\r\n    <span style=\"color: #007788; font-weight: bold;\">bool<\/span> is_valid() { <span style=\"color: #006699; font-weight: bold;\">return<\/span> valid; }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> read();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ read from f<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>()\r\n{\r\n    X3 file {<span style=\"color: #cc3300;\">\"Heraclides\"<\/span>};\r\n    file.read();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ crash or bad read!<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (file.is_valid()) {\r\n        file.read();\r\n        <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    }\r\n    <span style=\"color: #006699; font-weight: bold;\">else<\/span> {\r\n        <span style=\"color: #0099ff; font-style: italic;\">\/\/ ... handle error ...<\/span>\r\n    }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C43_Ensure_that_a_value_type_class_has_a_default_constructor\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-default0\">C.43: Ensure that a value type class has a default constructor<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>A value type is a type that behaves like an <span style=\"font-family: courier new,courier;\">int.<\/span> A value type is similar to a regular type. I wrote about value types and regular types in the post about <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-class-rules\">concrete types<\/a>. Having a default constructor makes it easier to use your type. Many constructors of STL containers rely on the fact that your type has a default constructor. For example, for the value of an ordered associative container such as <span style=\"font-family: courier new,courier;\">std::map<\/span>. If all the class members have a default constructor, the compiler will implicitly generate one for your class.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C44_Prefer_default_constructors_to_be_simple_and_non-throwing\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-default00\">C.44: Prefer default constructors to be simple and non-throwing<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Error handling is a lot easier with default constructors that can not throw. The guidelines provide a simple example:<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ elem is nullptr or elem points to space-elem element allocated using new<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Vector1<\/span> {\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ sets the representation to {nullptr, nullptr, nullptr}; doesn't throw<\/span>\r\n    Vector1() noexcept {}\r\n    Vector1(<span style=\"color: #007788; font-weight: bold;\">int<\/span> n) <span style=\"color: #555555;\">:<\/span>elem{<span style=\"color: #006699; font-weight: bold;\">new<\/span> T[n]}, space{elem <span style=\"color: #555555;\">+<\/span> n}, last{elem} {}\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n<span style=\"color: #9999ff;\">private:<\/span>\r\n    own<span style=\"color: #555555;\">&lt;<\/span>T<span style=\"color: #555555;\">*&gt;<\/span> elem <span style=\"color: #555555;\">=<\/span> nullptr;\r\n    T<span style=\"color: #555555;\">*<\/span> space <span style=\"color: #555555;\">=<\/span> nullptr;\r\n    T<span style=\"color: #555555;\">*<\/span> last <span style=\"color: #555555;\">=<\/span> nullptr;\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C45_Dont_define_a_default_constructor_that_only_initializes_data_members_use_member_initializers_instead\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-default\">C.45: Don\u2019t define a default constructor that only initializes data members; use member initializers instead<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>This is one of my favorite features of C++11. Initializing class members directly in the class body makes the writing of constructors a lot easier and sometimes obsolete. Class <span style=\"font-family: courier new,courier;\">X1<\/span> classically defines its members (before C++11) and <span style=\"font-family: courier new,courier;\">X2<\/span> in a preferred way. A nice side effect is that the compiler automatically generates the constructor for <span style=\"font-family: courier new,courier;\">X2<\/span>.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X1<\/span> { <span style=\"color: #0099ff; font-style: italic;\">\/\/ BAD: doesn't use member initializers<\/span>\r\n    string s;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    X1() <span style=\"color: #555555;\">:<\/span>s{<span style=\"color: #cc3300;\">\"default\"<\/span>}, i{<span style=\"color: #ff6600;\">1<\/span>} { }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X2<\/span> {\r\n    string s <span style=\"color: #555555;\">=<\/span> <span style=\"color: #cc3300;\">\"default\"<\/span>;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">1<\/span>;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ use compiler-generated default constructor<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C46_By_default_declare_single-argument_constructors_explicit\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-explicit\">C.46: By default, declare single-argument constructors <code class=\"highlighter-rouge no-highlight\">explicit<\/code><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>This is a crucial rule. Single-argument constructors are often called conversion constructors. If you make them not explicit, an implicit conversion may happen.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">String<\/span> {\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">explicit<\/span> String(<span style=\"color: #007788; font-weight: bold;\">int<\/span>);  \/\/ explicit\r\n    \/\/ String(int);        \/\/ implicit\r\n};\r\n\r\nString s <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">10<\/span>;            <span style=\"color: #0099ff; font-style: italic;\">\/\/ error because of explicit <br \/><\/span><\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The implicit conversion from <span style=\"font-family: courier new,courier;\">int<\/span> to <span style=\"font-family: courier new,courier;\">String<\/span> is impossible because the constructor is explicit. If instead of the explicit constructor, the out-commented implicit constructor were used, you would get a string of size 10<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C47_Define_and_initialize_member_variables_in_the_order_of_member_declaration\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-order\">C.47: Define and initialize member variables in the order of member declaration<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The class members are initialized in the order of their declaration. If you initialize them in the constructor initializer in a different order, you may get surprised.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Foo<\/span> {\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> m1;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> m2;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    Foo(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x) <span style=\"color: #555555;\">:<\/span>m2{x}, m1{<span style=\"color: #555555;\">++<\/span>x} { }   <span style=\"color: #0099ff; font-style: italic;\">\/\/ BAD: misleading initializer order<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\nFoo <span style=\"color: #cc00ff;\">x<\/span>(<span style=\"color: #ff6600;\">1<\/span>); <span style=\"color: #0099ff; font-style: italic;\">\/\/ surprise: x.m1 == x.m2 == 2<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C48_Prefer_in-class_initializers_to_member_initializers_in_constructors_for_constant_initializers\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-in-class-initializer\">C.48: Prefer in-class initializers to member initializers in constructors for constant initializers<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In-class initializer makes it a lot easier to define the constructors. Additionally, you can not forget to initialize a member.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X<\/span> {   <span style=\"color: #0099ff; font-style: italic;\">\/\/ BAD<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i;\r\n    string s;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> j;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    X() <span style=\"color: #555555;\">:<\/span>i{<span style=\"color: #ff6600;\">666<\/span>}, s{<span style=\"color: #cc3300;\">\"qqq\"<\/span>} { }   <span style=\"color: #0099ff; font-style: italic;\">\/\/ j is uninitialized<\/span>\r\n    X(<span style=\"color: #007788; font-weight: bold;\">int<\/span> ii) <span style=\"color: #555555;\">:<\/span>i{ii} {}         <span style=\"color: #0099ff; font-style: italic;\">\/\/ s is \"\" and j is uninitialized<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X2<\/span> {\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i {<span style=\"color: #ff6600;\">666<\/span>};\r\n    string s {<span style=\"color: #cc3300;\">\"qqq\"<\/span>};\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> j {<span style=\"color: #ff6600;\">0<\/span>};\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    X2() <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">default<\/span>;        <span style=\"color: #0099ff; font-style: italic;\">\/\/ all members are initialized to their defaults<\/span>\r\n    X2(<span style=\"color: #007788; font-weight: bold;\">int<\/span> ii) <span style=\"color: #555555;\">:<\/span>i{ii} {}   <span style=\"color: #0099ff; font-style: italic;\">\/\/ s and j initialized to their defaults  (1)<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>While the in-class initialization establishes the default behavior of an object, the constructor (1) allows the variation of the default behavior.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C49_Prefer_initialization_to_assignment_in_constructors\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-initialize\">C.49: Prefer initialization to assignment in constructors<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>That is quite an old rule. The most obvious pros of initialization to the assignment are that you can not forget to assign a value and use it uninitialized. Initialization may be faster but never slower than assignment.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">B<\/span> {   <span style=\"color: #0099ff; font-style: italic;\">\/\/ BAD<\/span>\r\n    string s1;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    B() { s1 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #cc3300;\">\"Hello, \"<\/span>; }   <span style=\"color: #0099ff; font-style: italic;\">\/\/ BAD: default constructor followed by assignment<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span class=\"ez-toc-section\" id=\"C50_Use_a_factory_function_if_you_need_%E2%80%9Cvirtual_behavior%E2%80%9D_during_initialization\"><\/span><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-factory\">C.50: Use a factory function if you need \u201cvirtual behavior\u201d during initialization<\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Calling a virtual function from a constructor will not work as expected. For protection reasons, the virtual call mechanism is disabled in the constructor because the creation of the derived class hasn&#8217;t happened.<\/p>\n<p>Hence, the following example will call the Base version of the virtual function f.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ virtualConstructor.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Base{\r\n  Base(){\r\n    f();\r\n  }\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> f(){\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Base called\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived<span style=\"color: #555555;\">:<\/span> Base{\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> f(){\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Derived called\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  \r\n  Derived d;         \r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  \r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>&nbsp;Here is the output of the program.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignleft size-full wp-image-5312\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/virtualConstructor.png\" alt=\"virtualConstructor\" width=\"350\" height=\"119\" style=\"float: left;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/virtualConstructor.png 435w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/virtualConstructor-300x102.png 300w\" sizes=\"auto, (max-width: 350px) 100vw, 350px\" \/><\/p>\n<h3><span class=\"ez-toc-section\" id=\"i\"><\/span>&nbsp;<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<h3><span class=\"ez-toc-section\" id=\"i-2\"><\/span>&nbsp;<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<h3><span class=\"ez-toc-section\" id=\"i-3\"><\/span>&nbsp;<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Let&#8217;s create a<a href=\"https:\/\/en.wikipedia.org\/wiki\/Factory_method_pattern\"> factory function <\/a>to have virtual behavior during object initialization. To deal with the ownership, the factory function should return a smart pointer such as a <span style=\"font-family: courier new,courier;\">std::unique_ptr<\/span> or a <span style=\"font-family: courier new,courier;\">std::shared_ptr. <\/span>As a starting point, I will use the previous example but make the constructor of <span style=\"font-family: courier new,courier;\">Base<\/span> protected; therefore, only objects of the class <span style=\"font-family: courier new,courier;\">Derived<\/span> can be created.<span style=\"font-family: courier new,courier;\"><br \/><\/span><\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ virtualInitialisation.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;memory&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Base<\/span>{\r\n<span style=\"color: #9999ff;\">protected:<\/span>\r\n  Base() <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">default<\/span>;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>(){                                            <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Base called\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;                   \r\n  }\r\n  <span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">T<\/span><span style=\"color: #555555;\">&gt;<\/span>                                              \r\n  <span style=\"color: #006699; font-weight: bold;\">static<\/span> std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>T<span style=\"color: #555555;\">&gt;<\/span> CreateMe(){                        <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2) <\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">auto<\/span> uniq <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>T<span style=\"color: #555555;\">&gt;<\/span>();\r\n    uniq<span style=\"color: #555555;\">-&gt;<\/span>f();                                                 <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> uniq;\r\n  }\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #555555;\">~<\/span>Base() <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">default<\/span>;                                   <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived<span style=\"color: #555555;\">:<\/span> Base{\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> f(){\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Derived called\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Base<span style=\"color: #555555;\">&gt;<\/span> base <span style=\"color: #555555;\">=<\/span> Derived<span style=\"color: #555555;\">::<\/span>CreateMe<span style=\"color: #555555;\">&lt;<\/span>Derived<span style=\"color: #555555;\">&gt;<\/span>();   <span style=\"color: #0099ff; font-style: italic;\">\/\/ (5)<\/span>\r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  \r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>At the end of the initialization, the virtual function<span style=\"font-family: courier new,courier;\"> f<\/span> (1) should be called. (2) is the factory function. This factory function calls <span style=\"font-family: courier new,courier;\">f<\/span> after creating a <span style=\"font-family: courier new,courier;\">std::unique_ptr <\/span>and returns it<span style=\"font-family: courier new,courier;\">.<\/span> If <span style=\"font-family: courier new,courier;\">Derived<\/span> is derived from <span style=\"font-family: courier new,courier;\">Base,<\/span> then<span style=\"font-family: courier new,courier;\"> <span style=\"font-family: courier new,courier;\">std::unique_ptr&lt;Dervived&gt;<\/span> <\/span>is implicitly convertible to a<span style=\"font-family: courier new,courier;\"> <span style=\"font-family: courier new,courier;\">std::unique_ptr&lt;Base&gt;<\/span>.<\/span> Finally, we get our virtual behavior during initialization.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5313\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/virtualInitialisation.png\" alt=\"virtualInitialisation\" width=\"350\" height=\"119\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/virtualInitialisation.png 435w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/virtualInitialisation-300x102.png 300w\" sizes=\"auto, (max-width: 350px) 100vw, 350px\" \/><\/p>\n<p>There is one risk with this technique. If the<span style=\"font-family: courier new,courier;\"> base<\/span> goes out of scope, you must ensure that the Derived destructor is called. This is the reason for the virtual destructor of <span style=\"font-family: courier new,courier;\">Base<\/span> (4).&nbsp; If the destructor is not virtual, you will get undefined behavior. Strange, but if I used a <span style=\"font-family: courier new,courier;\">std::shared_ptr<\/span> instead of a <span style=\"font-family: courier new,courier;\">std::unique_ptr<\/span> for the factory method, the virtual destructor of <span style=\"font-family: courier new,courier;\">Base<\/span> is unnecessary.&nbsp;<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Whats_next\"><\/span>What&#8217;s next?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Sorry, the post is a little bit too long. But I found, in particular, the last rule (C.50) very interesting; therefore, I had to explain more than usual. In the <a href=\"https:\/\/goo.gl\/1Fz59Q\">next post<\/a>, I will finish the rules for constructors and start with the copy and move rules.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The lifecycle of each object starts with its creation; therefore, this post will be about the thirteen most fundamental rules for objects: constructor rules.<\/p>\n","protected":false},"author":21,"featured_media":5311,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[499],"class_list":["post-5314","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-classes"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5314","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5314"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5314\/revisions"}],"predecessor-version":[{"id":6861,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5314\/revisions\/6861"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5311"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5314"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5314"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5314"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}