2-Member-functions.ipynb 15.3 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) - [Member functions](./2-Member-functions.ipynb)"
8
9
   ]
  },
10
11
12
13
14
15
16
17
18
19
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>Table of contents<span class=\"tocSkip\"></span></h1>\n",
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Member-functions\" data-toc-modified-id=\"Member-functions-1\">Member functions</a></span></li><li><span><a href=\"#The-this-keyword\" data-toc-modified-id=\"The-this-keyword-2\">The <code>this</code> keyword</a></span></li><li><span><a href=\"#Separating-declaration-and-definition\" data-toc-modified-id=\"Separating-declaration-and-definition-3\">Separating declaration and definition</a></span></li><li><span><a href=\"#Const-methods\" data-toc-modified-id=\"Const-methods-4\">Const methods</a></span><ul class=\"toc-item\"><li><span><a href=\"#mutable-keyword\" data-toc-modified-id=\"mutable-keyword-4.1\"><code>mutable</code> keyword</a></span></li></ul></li></ul></div>"
   ]
  },
20
21
22
23
24
25
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Member functions\n",
    "\n",
26
    "The struct we used previously would work the same in C code (with the exceptions of references: with a C compiler you would have to stick with pointers).\n",
27
28
29
    "\n",
    "But when Bjarne Stroustrup created the C++, its main idea was to extend these structs into full-fledged **classes** (to the point the work name of his language was *C with classes*...)\n",
    "\n",
30
    "One of the idea that was missing with original C `struct` was the possibility to add as well member functions; this is no longer the case:"
31
32
33
34
   ]
  },
  {
   "cell_type": "code",
35
   "execution_count": null,
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <cmath>\n",
    "\n",
    "struct Vector\n",
    "{\n",
    "    double x;\n",
    "    double y;    \n",
    "    double z;\n",
    "    \n",
    "    void init(double x, double y, double z)\n",
    "    {\n",
    "        this->x = x;\n",
    "        this->y = y;\n",
    "        this->z = z;\n",
    "    }\n",
    "    \n",
    "    double norm()\n",
    "    {\n",
    "        return std::sqrt(x * x + y * y + z * z);\n",
    "    }\n",
    "    \n",
    "};"
   ]
  },
  {
   "cell_type": "code",
64
65
66
   "execution_count": null,
   "metadata": {},
   "outputs": [],
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    Vector v;\n",
    "    v.init(5., 6., -4.2);\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's do a bit of taxonomy here:\n",
    "\n",
83
    "- `init()` and `norm()` are called **member functions** or **methods**. The same remark concerning C++ purist I did for member variables may be applied here.\n",
84
    "- **Method** is used in other programming languages, but for some reason Julia creators used this exact term for an entirely different concept. So to put in a nutshell a C++ method is akin to a Python one but not to what Julia calls a method.\n",
85
    "- **Attributes** are in fact the data attributes AND the methods. It is however often used only to designate the data attributes.\n",
86
    "\n",
87
    "**WARNING**: In C++ you can't complete a class after the fact as you could for instance in Python. So all the methods and data atttributes have to be declared within the struct brackets here; if you need to add something you will have to recompile the class. This means especially you can't add directly a member function to a class provided by a third party library; we'll see shortly the mechanism you may use instead to do your bidding."
88
89
90
91
92
93
94
95
96
97
98
99
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The `this` keyword\n",
    "\n",
    "The `this->` may have puzzled you: it is a keyword to refer to the current object. So when you call `v.init(...)`, this is an implicit reference to `v`.\n",
    "\n",
    "In most cases, it might be altogether removed; we have to put it explicitly here solely because we named the `init` parameters with the same name as the data attribute. If not, we could have avoided to mention it completely.\n",
    "\n",
GILLES Sebastien's avatar
Typo.    
GILLES Sebastien committed
100
    "An usual convention is to suffix data attributes with a `_` (**be careful**, attributes prefixed with a `_` is reserved by the C++ standard); doing so remove the need to the explicit `this`:"
101
102
103
104
   ]
  },
  {
   "cell_type": "code",
105
   "execution_count": null,
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <cmath>\n",
    "\n",
    "struct Vector2\n",
    "{\n",
    "    double x_;\n",
    "    double y_;    \n",
    "    double z_;\n",
    "    \n",
    "    void init(double x, double y, double z)\n",
    "    {\n",
    "        x_ = x;\n",
    "        y_ = y;\n",
    "        z_ = z;\n",
    "    }\n",
    "    \n",
    "    double norm()\n",
    "    {\n",
    "        return std::sqrt(x_ * x_ + y_ * y_ + z_ * z_);\n",
    "    }\n",
    "    \n",
    "};"
   ]
  },
  {
   "cell_type": "code",
134
135
136
   "execution_count": null,
   "metadata": {},
   "outputs": [],
137
138
139
140
141
142
143
144
145
146
147
148
149
150
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    Vector2 v;\n",
    "    v.init(5., 6., -4.2);\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
151
    "That is not to say you should forget altogether the `this` keyword: it might be necessary in some contexts (for templates for instance - see [later](../4-Templates/3-Syntax.ipynb)...)"
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Separating declaration and definition\n",
    "\n",
    "We have defined above the method directly in the class declaration; which is not very clean. It is acceptable for a very short method as here, but for a more complex class and method it is better to separate explicitly both. In this case you will have:\n",
    "\n",
    "- On one side, usually in a header file:\n"
   ]
  },
  {
   "cell_type": "code",
167
   "execution_count": null,
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
   "metadata": {},
   "outputs": [],
   "source": [
    "struct Vector3\n",
    "{\n",
    "    double x_;\n",
    "    double y_;    \n",
    "    double z_;\n",
    "    \n",
    "    void init(double x, double y, double z);\n",
    "    \n",
    "    double norm();\n",
    "};"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- On another side the definition, usually in a source file which includes the header file:"
   ]
  },
  {
   "cell_type": "code",
192
   "execution_count": null,
193
194
195
196
197
198
199
200
201
202
203
204
205
   "metadata": {},
   "outputs": [],
   "source": [
    "void Vector3::init(double x, double y, double z)\n",
    "{\n",
    "    x_ = x;\n",
    "    y_ = y;\n",
    "    z_ = z;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
206
   "execution_count": null,
207
208
209
210
211
212
213
214
215
216
217
   "metadata": {},
   "outputs": [],
   "source": [
    "double Vector3::norm()\n",
    "{\n",
    "    return std::sqrt(x_ * x_ + y_ * y_ + z_ * z_);\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
218
219
220
   "execution_count": null,
   "metadata": {},
   "outputs": [],
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    Vector3 v;\n",
    "    v.init(5., 6., -4.2);\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Please notice the `::` syntax which specifies the class for which the implementation is provided. Also pay attention to the fact the `this` may as well be implicitly used."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Const methods\n",
    "\n",
    "Are we happy here with what we have so far? Unfortunately, not quite...\n",
    "\n",
    "If we define a simple free function that print the norm of a `Vector3`:"
   ]
  },
  {
   "cell_type": "code",
251
252
253
   "execution_count": null,
   "metadata": {},
   "outputs": [],
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
   "source": [
    "#include <iostream>\n",
    "\n",
    "void print_norm(const Vector3& v)\n",
    "{\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "... we see that doesn't compile. So what is happening?\n",
    "\n",
    "The issue here is that the function `print_norm` takes as argument a constant reference, and has to guarantee the underlying object is not modified in the process. A \"patch\" would be to define it without the const:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
275
   "execution_count": null,
276
277
278
279
280
281
282
283
284
285
286
287
288
   "metadata": {},
   "outputs": [],
   "source": [
    "#include <iostream>\n",
    "\n",
    "void print_norm_no_const(Vector3& v) // BAD IDEA!\n",
    "{\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
289
290
291
   "execution_count": null,
   "metadata": {},
   "outputs": [],
292
293
294
295
296
297
298
299
300
301
302
303
   "source": [
    "{\n",
    "    Vector3 v;\n",
    "    v.init(5., 6., -4.2);\n",
    "    print_norm_no_const(v);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
304
    "Why is it such a poor idea? C++ is a compiled language, and this has its (many) pros and (many) cons. One of the advantages is to be able to leverage the compilation to detect at early time something is amiss. Here the compilation error is a good way to see we might be doing something wrong.\n",
305
306
307
308
309
310
311
312
    "\n",
    "The sketchy \"patch\" I provided would be akin to ignoring the `const` feature almost entirely when objects are concerned.\n",
    "\n",
    "The proper way is in fact quite the opposite: we may specify when writing a method that it is not allowed to modify the state of the object:"
   ]
  },
  {
   "cell_type": "code",
313
   "execution_count": null,
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
   "metadata": {},
   "outputs": [],
   "source": [
    "struct Vector4\n",
    "{\n",
    "    double x_;\n",
    "    double y_;    \n",
    "    double z_;\n",
    "    \n",
    "    void init(double x, double y, double z);\n",
    "    \n",
    "    double norm() const; // notice the additional keyword!\n",
    "    \n",
    "    void dont_put_const_everywhere() const;\n",
    "};"
   ]
  },
  {
   "cell_type": "code",
333
   "execution_count": null,
334
335
336
337
338
339
340
341
342
343
344
345
346
   "metadata": {},
   "outputs": [],
   "source": [
    "void Vector4::init(double x, double y, double z)\n",
    "{\n",
    "    x_ = x;\n",
    "    y_ = y;\n",
    "    z_ = z;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
347
   "execution_count": null,
348
349
350
351
352
353
354
355
356
357
358
359
360
   "metadata": {},
   "outputs": [],
   "source": [
    "double Vector4::norm() const\n",
    "{\n",
    "    return std::sqrt(x_ * x_ + y_ * y_ + z_ * z_);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
361
    "Please notice `const` needs to be specified both on declaration and on definition: if not provided in definition the signature of the method won't match and the compiler will yell."
362
363
364
365
   ]
  },
  {
   "cell_type": "code",
366
367
368
   "execution_count": null,
   "metadata": {},
   "outputs": [],
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
   "source": [
    "#include <iostream>\n",
    "\n",
    "void print_norm(const Vector4& v)\n",
    "{\n",
    "    std::cout << v.norm() << std::endl;\n",
    "}\n",
    "\n",
    "{\n",
    "    Vector4 v;\n",
    "    v.init(5., 6., -4.2);\n",
    "    print_norm(v);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Obviously, if we try to ignore a `const` keyword, the compiler will also yell (it is and SHOULD BE very good at this!):"
   ]
  },
  {
   "cell_type": "code",
393
394
395
   "execution_count": null,
   "metadata": {},
   "outputs": [],
396
397
398
399
400
401
402
403
404
405
406
407
408
   "source": [
    "void Vector4::dont_put_const_everywhere() const\n",
    "{\n",
    "    x_ = 0.; // ERROR!\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `mutable` keyword\n",
    "\n",
409
    "Tread here with extreme caution here! Sometimes, you might want for a method to be mostly unable to modify the state of the class but you still need to modify one or more attribute. You may in this case use the `mutable` keyword when defining this attribute:"
410
411
412
413
   ]
  },
  {
   "cell_type": "code",
414
   "execution_count": null,
415
416
417
418
419
420
421
422
423
424
425
426
   "metadata": {},
   "outputs": [],
   "source": [
    "struct Vector5\n",
    "{\n",
    "    double x_;\n",
    "    double y_;    \n",
    "    double z_;\n",
    "    mutable unsigned int Nnorm_calls_;\n",
    "    \n",
    "    void init(double x, double y, double z);\n",
    "    \n",
427
    "    double norm() const; \n",
428
429
430
431
432
    "};"
   ]
  },
  {
   "cell_type": "code",
433
   "execution_count": null,
434
435
436
437
438
439
440
441
442
443
444
445
446
447
   "metadata": {},
   "outputs": [],
   "source": [
    "void Vector5::init(double x, double y, double z)\n",
    "{\n",
    "    x_ = x;\n",
    "    y_ = y;\n",
    "    z_ = z;\n",
    "    Nnorm_calls_ = 0u;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
448
   "execution_count": null,
449
450
451
452
453
454
455
456
457
458
459
460
   "metadata": {},
   "outputs": [],
   "source": [
    "double Vector5::norm() const\n",
    "{\n",
    "    ++Nnorm_calls_;\n",
    "    return std::sqrt(x_ * x_ + y_ * y_ + z_ * z_);\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
461
462
463
   "execution_count": null,
   "metadata": {},
   "outputs": [],
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
   "source": [
    "{\n",
    "    Vector5 v;\n",
    "    v.init(5., 6., -4.2);\n",
    "    for (int i = 0; i < 5; ++i)\n",
    "        v.norm();\n",
    "    std::cout << \"Method 'norm()' was called \" << v.Nnorm_calls_ << \" times.\" << std::endl;    \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I must stress again that you should use this in a **last resort**! \n",
    "\n",
    "For my part, I have used this in only two contexts:\n",
    "* Using a work variable that would have been costly to reallocate at each call. This variable was always reset and used within the method that calls it and was not used to share a state between methods.\n",
    "* For mutexes when using shared memory parallelism. This is way out of the scope of this tutorial."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
489
    "© _CNRS 2016_ - _Inria 2018-2021_   \n",
490
491
    "_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)_"
492
493
494
495
496
497
498
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++17",
   "language": "C++17",
499
   "name": "xcpp17"
500
501
502
503
504
505
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "c++",
506
   "version": "17"
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "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": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "318.8px"
   },
   "toc_section_display": true,
542
   "toc_window_display": false
543
544
545
  }
 },
 "nbformat": 4,
546
 "nbformat_minor": 4
547
}