3-constructors-destructor.ipynb 26.8 KB
Newer Older
1 2 3 4 5 6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
7
    "# [Getting started in C++](./) - [Object programming](./0-main.ipynb) - [(Base) constructors and destructor](./3-constructors-destructor.ipynb)"
8 9
   ]
  },
10 11 12 13 14 15 16
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>Table of contents<span class=\"tocSkip\"></span></h1>\n",
17
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Introduction-to-base-constructor\" data-toc-modified-id=\"Introduction-to-base-constructor-1\">Introduction to base constructor</a></span><ul class=\"toc-item\"><li><span><a href=\"#[WARNING]-How-to-call-a-constructor-without-argument\" data-toc-modified-id=\"[WARNING]-How-to-call-a-constructor-without-argument-1.1\"><strong>[WARNING]</strong> How to call a constructor without argument</a></span></li><li><span><a href=\"#&quot;Auto-to-stick&quot;-syntax-for-constructor-calls\" data-toc-modified-id=\"&quot;Auto-to-stick&quot;-syntax-for-constructor-calls-1.2\">\"Auto-to-stick\" syntax for constructor calls</a></span></li></ul></li><li><span><a href=\"#Initializing-a-reference-data-attribute\" data-toc-modified-id=\"Initializing-a-reference-data-attribute-2\">Initializing a reference data attribute</a></span></li><li><span><a href=\"#Delegating-constructor\" data-toc-modified-id=\"Delegating-constructor-3\">Delegating constructor</a></span></li><li><span><a href=\"#Default-constructor\" data-toc-modified-id=\"Default-constructor-4\">Default constructor</a></span></li><li><span><a href=\"#Good-practice:-provide-in-the-data-attribute-declaration-a-default-value\" data-toc-modified-id=\"Good-practice:-provide-in-the-data-attribute-declaration-a-default-value-5\">Good practice: provide in the data attribute declaration a default value</a></span></li><li><span><a href=\"#Good-practice:-define-the-attribute-in-the-same-order-they-are-defined\" data-toc-modified-id=\"Good-practice:-define-the-attribute-in-the-same-order-they-are-defined-6\">Good practice: define the attribute in the same order they are defined</a></span></li><li><span><a href=\"#Good-practice:-use-explicit-constructors-by-default\" data-toc-modified-id=\"Good-practice:-use-explicit-constructors-by-default-7\">Good practice: use <code>explicit</code> constructors by default</a></span></li><li><span><a href=\"#Destructor\" data-toc-modified-id=\"Destructor-8\">Destructor</a></span><ul class=\"toc-item\"><li><span><a href=\"#Default-destructor\" data-toc-modified-id=\"Default-destructor-8.1\">Default destructor</a></span></li></ul></li></ul></div>"
18 19
   ]
  },
20 21 22 23 24 25 26 27
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction to base constructor\n",
    "\n",
    "In fact, our previous `init()` function is meant to be realized through a dedicated method called a **constructor**. By convention, a constructor shares the name of the struct or class.\n",
    "\n",
28
    "Several constructors may be defined for a given class, provided there is no signature overlap."
29 30 31 32
   ]
  },
  {
   "cell_type": "code",
33
   "execution_count": null,
34 35 36
   "metadata": {},
   "outputs": [],
   "source": [
37
    "struct Vector\n",
38 39 40 41 42
    "{\n",
    "    double x_;\n",
    "    double y_;    \n",
    "    double z_;\n",
    "    \n",
43
    "    Vector(); // Constructor\n",
44
    "    \n",
45
    "    Vector(double x, double y, double z); // Another constructor\n",
46 47 48 49 50
    "    \n",
    "    double norm() const;\n",
    "};"
   ]
  },
51 52 53 54 55 56 57
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data attributes may be initialized more efficiently with a special syntax shown below:"
   ]
  },
58 59
  {
   "cell_type": "code",
60
   "execution_count": null,
61 62 63
   "metadata": {},
   "outputs": [],
   "source": [
64 65
    "Vector::Vector(double x, double y, double z)\n",
    ": x_(x), // See the syntax here: `:` to introduce data attributes initialization,\n",
66 67
    "y_(y), // and commas to separate the different data attributes.\n",
    "z_(z)\n",
68 69
    "{ \n",
    "}"
70 71 72 73
   ]
  },
  {
   "cell_type": "code",
74
   "execution_count": null,
75 76 77
   "metadata": {},
   "outputs": [],
   "source": [
78
    "Vector::Vector()\n",
79
    ": x_(0.), // braces may also be used since C++ 11... but not supported here by Xeus-cling.\n",
80 81 82 83 84 85 86
    "y_(0.),\n",
    "z_(0.)\n",
    "{ }"
   ]
  },
  {
   "cell_type": "code",
87
   "execution_count": null,
88 89 90
   "metadata": {},
   "outputs": [],
   "source": [
91
    "double Vector::norm() const\n",
92 93 94 95 96 97 98
    "{\n",
    "    return std::sqrt(x_ * x_ + y_ * y_ + z_ * z_);\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
99
   "execution_count": null,
100
   "metadata": {},
101
   "outputs": [],
102 103 104 105
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
106
    "    Vector v(5., 6., -4.2); // note the creation of an object with a constructor call.\n",
107 108 109 110 111 112 113 114
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
115
    "### **[WARNING]** How to call a constructor without argument\n",
116
    "\n",
117
    "There is a technicality for constructor without arguments: they must be called **without** parenthesis (the reason is a possible confusion with a [functor](../3-Operators/5-Functors.ipynb) - see Item 6 of \\cite{Meyers2001} or [this blog post](https://www.fluentcpp.com/2018/01/30/most-vexing-parse/) if you want to learn more about the reasons of this):"
118 119 120 121
   ]
  },
  {
   "cell_type": "code",
122
   "execution_count": null,
123
   "metadata": {},
124
   "outputs": [],
125 126 127 128
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
129
    "    Vector v; // no parenthesis here!\n",
130 131 132 133
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### \"Auto-to-stick\" syntax for constructor calls\n",
    "\n",
    "A way to avoid the mistake entirely is to call the so-called \"auto-to-stick\" alternate syntax:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    auto v = Vector(5, 10, 15); // auto-to-stick syntax: a new perfectly fine way to declare an object.\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This syntax completely removes the ambiguity: you **have to** keep the `()`, so the constructor with no arguments doesn't become a special case that is handled differently."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "{\n",
    "    auto v = Vector(); // auto-to-stick syntax\n",
    "    std::cout << v.norm() << std::endl;    \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
180
    "This auto-to-stick syntax is not widely used, but is advised by some developers as a natural evolution of the syntax of the language (it is very akin to the [alternate syntax for functions](../1-ProceduralProgramming/4-Functions.ipynb#Alternate-function-syntax) we saw earlier). \n",
181 182 183 184
    "\n",
    "I advise you to read this very interesting [FluentCpp post](https://www.fluentcpp.com/2018/09/28/auto-stick-changing-style/) about this syntax which ponders about the relunctance we might have to embrace evolution of our languages - so the reading is of interest even for developers using other languages."
   ]
  },
185 186 187 188 189 190 191 192 193 194 195
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initializing a reference data attribute\n",
    "\n",
    "We saw above a new syntax to initialize data attributes, but there is no harm defining the same as we did in our former `init()` method. That is however not true when there is a reference data attribute, for which the reference must absolutely be defined with the new syntax:"
   ]
  },
  {
   "cell_type": "code",
196
   "execution_count": null,
197 198 199 200 201 202 203 204 205 206
   "metadata": {},
   "outputs": [],
   "source": [
    "struct First\n",
    "{\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
207
   "execution_count": null,
208 209 210 211 212 213 214 215 216 217 218 219 220 221
   "metadata": {},
   "outputs": [],
   "source": [
    "struct Second\n",
    "{\n",
    "    \n",
    "    const First& first_;\n",
    "    \n",
    "    Second(const First& first);\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
222
   "execution_count": null,
223
   "metadata": {},
224
   "outputs": [],
225 226 227 228 229 230 231 232 233
   "source": [
    "Second::Second(const First& first)\n",
    "{\n",
    "    first_ = first; // COMPILATION ERROR: can't initialize a reference data attribute here!    \n",
    "}"
   ]
  },
  {
   "cell_type": "code",
234
   "execution_count": null,
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
   "metadata": {},
   "outputs": [],
   "source": [
    "Second::Second(const First& first)\n",
    ": first_(first) // OK!\n",
    "{ } "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The reason for this behaviour is that the reference must be defined at the very moment the object is created, and in fact the body of a constructor is run _after_ the actual creation occurs. With the proper syntax, the data is properly initialized in the same time the object is created.\n",
    "\n",
    "\n",
    "## Delegating constructor\n",
    "\n",
    "Since C++ 11, it is possible to use a base constructor when defining another constructor:"
   ]
  },
  {
   "cell_type": "code",
257
   "execution_count": null,
258 259 260
   "metadata": {},
   "outputs": [],
   "source": [
261
    "struct Vector2\n",
262 263 264
    "{\n",
    "    double x_, y_, z_;\n",
    "    \n",
265
    "    Vector2();\n",
266
    "    \n",
267
    "    Vector2(double x);\n",
268
    "    \n",
269
    "    Vector2(double x, double y, double z);\n",
270 271 272 273 274 275 276
    "    \n",
    "    void Print() const;\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
277
   "execution_count": null,
278 279 280 281 282
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
283
    "void Vector2::Print() const\n",
284 285 286 287 288 289 290
    "{\n",
    "    std::cout << \"(x, y, z) = (\" << x_ << \", \" << y_ << \", \" << z_ << \")\" << std::endl << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
291
   "execution_count": null,
292 293 294 295 296
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
297
    "Vector2::Vector2()\n",
298 299 300 301
    ": x_(-1.),\n",
    "y_(-1.),\n",
    "z_(-1.)\n",
    "{\n",
302
    "    std::cout << \"Calling Vector2 constructor with no arguments.\" << std::endl;\n",
303 304 305 306 307
    "}"
   ]
  },
  {
   "cell_type": "code",
308
   "execution_count": null,
309 310 311
   "metadata": {},
   "outputs": [],
   "source": [
312
    "Vector2::Vector2(double x, double y, double z)\n",
313 314 315 316 317 318 319 320
    ": x_(x),\n",
    "y_(y),\n",
    "z_(z)\n",
    "{ }"
   ]
  },
  {
   "cell_type": "code",
321
   "execution_count": null,
322 323 324
   "metadata": {},
   "outputs": [],
   "source": [
325 326
    "Vector2::Vector2(double x)\n",
    ": Vector2() \n",
327 328 329 330 331 332 333 334
    "{ \n",
    "    x_ = x; // As the first constructor is assumed to build fully the object, you can't assign data attributes \n",
    "            // before the body of the constructor.\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
335
   "execution_count": null,
336
   "metadata": {},
337
   "outputs": [],
338 339 340
   "source": [
    "{\n",
    "    std::cout << \"Constructor with no argument:\" << std::endl;\n",
341
    "    Vector2 v1;\n",
342 343 344
    "    v1.Print();\n",
    "    \n",
    "    std::cout << \"Constructor with no delegation:\" << std::endl;\n",
345
    "    Vector2 v2(3., 7., 5.);\n",
346 347 348
    "    v2.Print();\n",
    "    \n",
    "    std::cout << \"Constructor that calls a delegate constructor:\" << std::endl;    \n",
349
    "    Vector2 v3(3.);\n",
350 351 352 353 354 355 356 357 358 359
    "    v3.Print();    \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Default constructor\n",
    "\n",
360
    "If in a `class` or `struct` no constructor is defined, a default one is assumed: it takes no argument and sports an empty body.\n",
361 362
    "\n",
    "As soon as another constructor is defined, this default constructor no longer exists:\n",
363
    "   "
364 365 366 367
   ]
  },
  {
   "cell_type": "code",
368
   "execution_count": null,
369 370 371 372 373 374 375 376 377
   "metadata": {},
   "outputs": [],
   "source": [
    "struct ClassWithoutConstructor\n",
    "{ };"
   ]
  },
  {
   "cell_type": "code",
378
   "execution_count": null,
379 380 381 382 383 384 385 386 387 388
   "metadata": {},
   "outputs": [],
   "source": [
    "{\n",
    "    ClassWithoutConstructor my_object;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
389
   "execution_count": null,
390 391 392 393 394 395 396 397 398 399 400
   "metadata": {},
   "outputs": [],
   "source": [
    "struct ClassWithConstructorWithArg\n",
    "{\n",
    "    ClassWithConstructorWithArg(int a);\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
401
   "execution_count": null,
402 403 404 405 406 407 408 409 410
   "metadata": {},
   "outputs": [],
   "source": [
    "ClassWithConstructorWithArg::ClassWithConstructorWithArg(int a)\n",
    "{ }"
   ]
  },
  {
   "cell_type": "code",
411
   "execution_count": null,
412
   "metadata": {},
413
   "outputs": [],
414 415 416 417 418 419 420 421 422 423
   "source": [
    "{\n",
    "    ClassWithConstructorWithArg my_object; // COMPILATION ERROR!\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
424
    "This must seem messy at first sight, but doing otherwise would be nightmarish: if you define a very complex class that must be carefully initialized with well thought-out arguments, you do not want your end-user to bypass this with a inconsiderate call to a constructor without arguments!\n",
425
    "\n",
426
    "If you want to enable back constructor without arguments, you may do so by defining it explicitly. C++11 introduced a nice way to do so (provided you wish an empty body - if not define it explicitly yourself):"
427 428 429 430
   ]
  },
  {
   "cell_type": "code",
431
   "execution_count": null,
432 433 434 435 436 437 438 439 440 441 442 443 444
   "metadata": {},
   "outputs": [],
   "source": [
    "struct ClassWithConstructorWithAndWithoutArg\n",
    "{\n",
    "    ClassWithConstructorWithAndWithoutArg() = default;\n",
    "        \n",
    "    ClassWithConstructorWithAndWithoutArg(int a);    \n",
    "};"
   ]
  },
  {
   "cell_type": "code",
445
   "execution_count": null,
446 447 448 449 450 451 452 453 454
   "metadata": {},
   "outputs": [],
   "source": [
    "ClassWithConstructorWithAndWithoutArg::ClassWithConstructorWithAndWithoutArg(int a)\n",
    "{ }"
   ]
  },
  {
   "cell_type": "code",
455
   "execution_count": null,
456 457 458 459 460 461 462 463 464 465 466 467
   "metadata": {},
   "outputs": [],
   "source": [
    "{\n",
    "    ClassWithConstructorWithAndWithoutArg my_object; // OK!\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
468
    "## Good practice: provide in the data attribute declaration a default value\n",
469 470 471 472 473 474
    "\n",
    "In a constructor, you are expected to initialize properly all the data attributes. You can't expect a default behaviour if you fail to do so:"
   ]
  },
  {
   "cell_type": "code",
475
   "execution_count": null,
476 477 478 479 480
   "metadata": {},
   "outputs": [],
   "source": [
    "struct BadlyInitialized\n",
    "{\n",
481
    "    int a_;\n",
482 483 484 485 486
    "};"
   ]
  },
  {
   "cell_type": "code",
487
   "execution_count": null,
488
   "metadata": {},
489
   "outputs": [],
490 491 492 493 494
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    BadlyInitialized my_object;\n",
495
    "    std::cout << \"Undefined behaviour: no guarantee for the value of the data attribute!: \" << my_object.a_ << std::endl;\n",
496 497 498 499 500 501 502
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
503
    "You are therefore supposed to define explicitly all the data attributes in all of your constructors. It was easy to get trumped by this in C++98/03: if you added a new data attribute and forgot to initialize it in one of your constructor, you would have undefined behaviour that is one of the worst bug to track down! (as on your machine/architecture you may have a \"good\" behaviour haphazardly).\n",
504 505 506 507 508 509
    "\n",
    "Fortunately, C++ 11 introduced a mechanism I strongly recommend to provide a default value:"
   ]
  },
  {
   "cell_type": "code",
510
   "execution_count": null,
511 512 513 514 515
   "metadata": {},
   "outputs": [],
   "source": [
    "struct SafeClass\n",
    "{\n",
516
    "    int a_ { 5 }; // The default value is provided here in the class declaration.        \n",
517 518 519 520 521 522 523 524 525
    "    \n",
    "    SafeClass() = default;\n",
    "    \n",
    "    SafeClass(int new_value);\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
526
   "execution_count": null,
527 528 529 530 531 532 533 534 535 536
   "metadata": {},
   "outputs": [],
   "source": [
    "SafeClass::SafeClass(int new_value)\n",
    ": a_(new_value)\n",
    "{ }"
   ]
  },
  {
   "cell_type": "code",
537
   "execution_count": null,
538
   "metadata": {},
539
   "outputs": [],
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    SafeClass no_Arg;\n",
    "    std::cout << \"If constructor doesn't change the value, default is used: \" << no_Arg.a_ << std::endl;\n",
    "    \n",
    "    \n",
    "    SafeClass modified(10);\n",
    "    std::cout << \"If constructor changes the value, choice is properly used: \" << modified.a_ << std::endl;\n",
    "   \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
STEFF Laurent's avatar
STEFF Laurent committed
558
    "Please notice doing so doesn't prevent you to use the efficient initialization of `a_` in the constructor with arguments: the values thus provided in the data attributes definitions are used only if the constructor doesn't supersede them.\n",
559
    "\n",
560
    "In the same spirit, if you get pointers as data attributes it is a good idea to set them by default to `nullptr`: this way you may check with an [`assert`](../5-UsefulConceptsAndSTL/1-ErrorHandling.ipynb#Assert) it has been correctly initialized before use."
561 562 563 564 565 566
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
STEFF Laurent's avatar
STEFF Laurent committed
567
    "## Good practice: define the attribute in the same order they are declared\n",
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    "\n",
    "Data attributes should be defined in the exact same order they are declared within the class. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "struct BadOrder\n",
    "{\n",
    "    BadOrder();\n",
    "    \n",
    "    int a_;\n",
    "    bool b_;\n",
    "};    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BadOrder::BadOrder()\n",
    ": b_(false), // WRONG: a_ should be defined before b_, as it is the order in which they are declared in the class.\n",
    "a_(5)\n",
    "{ }"
597 598 599 600 601 602
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
603
    "Unfortunately Xeus-cling doesn't issue the warning here, but I gather all normal compilers do (even the oldest versions of clang and gcc available on [Wandbox](https://wandbox.org/) do in the very least...).\n",
604
    "\n",
605
    "Most of the time it doesn't matter much, but if there are dependencies between attributes it might create havoc so take the habit to respect the ordering.\n",
606
    "\n",
STEFF Laurent's avatar
STEFF Laurent committed
607
    "Of course, you may not define explicitly a data attribute for which you provide a default value at declaration:"
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <string>\n",
    "\n",
    "struct OkOrder\n",
    "{\n",
    "    OkOrder(int a, float c);\n",
    "    \n",
    "    int a_ {0};\n",
    "    std::string b_ {\"default_text\"};    \n",
    "    float c_ {3.5f};\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "OkOrder::OkOrder(int a, float c)\n",
    ": a_(a),\n",
    "c_(c) // Ok!\n",
    "{ }"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
644
    "## Good practice: use `explicit` constructors by default\n",
645 646 647 648 649 650
    "\n",
    "Let's study the following case:"
   ]
  },
  {
   "cell_type": "code",
651
   "execution_count": null,
652 653 654 655 656 657 658 659 660 661 662
   "metadata": {},
   "outputs": [],
   "source": [
    "struct ClassWithIntConstructor\n",
    "{\n",
    "    ClassWithIntConstructor(int a);\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
663
   "execution_count": null,
664 665 666 667 668 669 670 671 672 673 674 675 676
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
    "ClassWithIntConstructor::ClassWithIntConstructor(int a)\n",
    "{\n",
    "    std::cout << \"Constructor called with argument \" << a << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
677
   "execution_count": null,
678
   "metadata": {},
679
   "outputs": [],
680 681
   "source": [
    "{\n",
682 683
    "    ClassWithIntConstructor my_object(5);\n",
    "    \n",
684
    "    my_object = 7.9; // Dubious but correct: assigning an integer!\n",
685 686 687 688 689 690 691
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
692
    "So what happens here? In fact, the compiler implicitly convert the integer read into a `ClassWithIntConstructor` constructor with an integer argument...\n",
693
    "\n",
694
    "There are situations in which this might be deemed the right thing to do (none to my mind but I guess it depends on your programming style) but more often than not it's not what is intended and a good old compiler yell would be much preferable.\n",
695
    "\n",
696
    "To do so, in C++ 11 you must stick the keyword **explicit** in the declaration in front of the constructor. Personally I tend to always provide it to my constructors, following the likewise advice by \\cite{Meyers2015}.\n"
697 698 699 700
   ]
  },
  {
   "cell_type": "code",
701
   "execution_count": null,
702 703 704 705 706 707 708 709 710 711 712
   "metadata": {},
   "outputs": [],
   "source": [
    "struct ClassWithExplicitIntConstructor\n",
    "{\n",
    "    explicit ClassWithExplicitIntConstructor(int a);\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
713
   "execution_count": null,
714 715 716 717 718 719 720 721 722 723 724 725 726
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
    "ClassWithExplicitIntConstructor::ClassWithExplicitIntConstructor(int a)\n",
    "{\n",
    "    std::cout << \"Constructor called with argument \" << a << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
727
   "execution_count": null,
728
   "metadata": {},
729
   "outputs": [],
730 731 732 733 734 735
   "source": [
    "{\n",
    "    ClassWithExplicitIntConstructor my_object(5);\n",
    "    \n",
    "    my_object = 7; // COMPILATION ERROR! YAY!\n",
    "}"
736 737 738 739
   ]
  },
  {
   "cell_type": "markdown",
740 741 742 743
   "metadata": {
    "toc-hr-collapsed": true,
    "toc-nb-collapsed": true
   },
744 745 746 747 748
   "source": [
    "## Destructor\n",
    "\n"
   ]
  },
749 750 751 752 753 754 755 756 757 758 759
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pendant of the constructor is the **destructor**, which is called when the object is terminated. Contrary to constructors, there is only one destructor for a given class, and by design it takes no parameter.\n",
    "\n",
    "The syntax is like a constructor with no parameter with an additional `~` in front of the name."
   ]
  },
  {
   "cell_type": "code",
760
   "execution_count": null,
761 762 763 764 765
   "metadata": {},
   "outputs": [],
   "source": [
    "struct Array\n",
    "{\n",
766
    "    Array(int unique_id, std::size_t array_size);\n",
767 768 769 770
    "    \n",
    "    ~Array(); // Destructor!    \n",
    "    \n",
    "    double* array_ = nullptr;\n",
771
    "    const int unique_id_;\n",
772 773 774 775 776
    "};"
   ]
  },
  {
   "cell_type": "code",
777
   "execution_count": null,
778 779 780
   "metadata": {},
   "outputs": [],
   "source": [
781 782
    "Array::Array(int unique_id, std::size_t array_size)\n",
    ": unique_id_(unique_id)\n",
783 784 785 786 787 788 789
    "{\n",
    "    array_ = new double[array_size];\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
790
   "execution_count": null,
791 792 793 794 795 796 797
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
    "Array::~Array()\n",
    "{\n",
798
    "    std::cout << \"Memory for array \" << unique_id_ << \" is properly freed here.\" << std::endl;\n",
799 800 801 802 803 804
    "    delete[] array_;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
805
   "execution_count": null,
806
   "metadata": {},
807
   "outputs": [],
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
   "source": [
    "{\n",
    "    Array array1(1, 5ul);\n",
    "    \n",
    "    {\n",
    "        Array array2(2, 3ul);\n",
    "        \n",
    "        {\n",
    "            Array array3(3, 5ul);\n",
    "        }\n",
    "        \n",
    "        Array array4(4, 2ul);        \n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It's important to notice the ordering here: as soon as an object becomes out of scope, it is immediately destroyed; the creation order doesn't matter at all!\n",
    "\n",
830
    "We will see a bit [later](/notebooks/5-UsefulConceptsAndSTL/2-RAII.ipynb) how to take advantage of this behaviour to write programs that do not leak memory.\n",
831 832 833 834 835 836 837 838 839
    "\n",
    "\n",
    "### Default destructor\n",
    "\n",
    "If not specified, C++ implicitly defines a destructor with an empty body. Personally I like even in this case to make it explicit, which is done the same way as for a constructor from C++11 onward:"
   ]
  },
  {
   "cell_type": "code",
840
   "execution_count": null,
841 842 843 844 845 846 847 848
   "metadata": {},
   "outputs": [],
   "source": [
    "struct MyClass\n",
    "{\n",
    "    \n",
    "    MyClass() = default; // explicit default constructor\n",
    "    \n",
849
    "    ~MyClass() = default; // explicit default destructor\n",
850 851 852
    "}"
   ]
  },
853 854 855 856 857 858 859
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is however a matter of personal taste; see for instance [this post from FluentCpp](https://www.fluentcpp.com/2019/04/23/the-rule-of-zero-zero-constructor-zero-calorie) for the opposite advice of not defining explicitly default constructor / destructor if you don't have to."
   ]
  },
860 861 862 863 864 865 866 867 868 869 870 871 872
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# References\n",
    "\n",
    "[<a id=\"cit-Meyers2001\" href=\"#call-Meyers2001\">Meyers2001</a>] Scott Meyers, ``_Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library_'',  2001.\n",
    "\n",
    "[<a id=\"cit-Meyers2015\" href=\"#call-Meyers2015\">Meyers2015</a>] Scott Meyers, ``_Effective modern C++: 42 specific ways to improve your use of C++11\n",
    "               and C++14_'',  2015.  [online](http://www.worldcat.org/oclc/890021237)\n",
    "\n"
   ]
  },
873 874 875 876
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
877
    "© _CNRS 2016_ - _Inria 2018-2021_   \n",
878 879
    "_This notebook is an adaptation of a lecture prepared by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_  \n",
    "_The present version has been written by Sébastien Gilles and Vincent Rouvreau (Inria)_"
880 881 882 883 884 885 886
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++17",
   "language": "C++17",
887
   "name": "xcpp17"
888 889 890 891 892 893
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "c++",
894
   "version": "17"
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "key",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table of contents",
   "title_sidebar": "Contents",
   "toc_cell": true,
   "toc_position": {},
   "toc_section_display": true,
925
   "toc_window_display": false
926 927 928
  }
 },
 "nbformat": 4,
929
 "nbformat_minor": 4
930
}