forked from aaronbloomfield/pdr
-
Notifications
You must be signed in to change notification settings - Fork 228
/
09-advanced-cpp.html
954 lines (835 loc) · 28.1 KB
/
09-advanced-cpp.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
597
598
599
600
601
602
603
604
605
606
607
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CS 2150: 09-advanced-cpp slide set</title>
<meta name="description" content="A set of slides for a course on Program and Data Representation">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="../slides/reveal.js/dist/reset.css">
<link rel="stylesheet" href="../slides/reveal.js/dist/reveal.css">
<link rel="stylesheet" href="../slides/reveal.js/dist/theme/black.css" id="theme">
<link rel="stylesheet" href="../slides/css/pdr.css">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="../slides/reveal.js/plugin/highlight/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? '../slides/reveal.js/css/print/pdf.scss' : '../slides/reveal.js/css/print/paper.scss';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="../slides/reveal.js/lib/js/html5shiv.js"></script>
<![endif]-->
<style>.reveal li { font-size:93%; line-height:120%; }</style>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section data-markdown id="cover"><script type="text/template">
# CS 2150
### Program and Data Representation
<p class='titlep'> </p>
<div class="titlesmall"><p>
<a href="http://www.cs.virginia.edu/~mrf8t">Mark Floryan</a> (mrf8t@virginia.edu)<br>
<a href="http://www.cs.virginia.edu/~asb">Aaron Bloomfield</a> (aaron@virginia.edu)<br>
<a href="http://github.com/uva-cs/pdr">@github</a> | <a href="index.html">↑</a> | <a href="./09-advanced-cpp.html?print-pdf"><img class="print" width="20" src="../slides/images/print-icon.png" style="top:0px;vertical-align:middle"></a>
</p></div>
<p class='titlep'> </p>
## Advanced C++
</script></section>
<section>
<h2>CS 2150 Roadmap</h2>
<table class="wide">
<tr><td colspan="3"><p class="center">Data Representation</p></td><td></td><td colspan="3"><p class="center">Program Representation</p></td></tr>
<tr>
<td class="top"><small> <br> <br>string<br> <br> <br> <br>int x[3]<br> <br> <br> <br>char x<br> <br> <br> <br>0x9cd0f0ad<br> <br> <br> <br>01101011</small></td>
<!-- image adapted from http://openclipart.org/detail/3677/arrow-left-right-by-torfnase -->
<td><img class="noborder" src="images/red-double-arrow.png" height="500" alt="vertical red double arrow"></td>
<td class="top"> <br>Objects<br> <br>Arrays<br> <br>Primitive types<br> <br>Addresses<br> <br>bits</td>
<td> </td>
<td class="top"><small> <br> <br>Java code<br> <br> <br>C++ code<br> <br> <br>C code<br> <br> <br>x86 code<br> <br> <br>IBCM<br> <br> <br>hexadecimal</small></td>
<!-- image adapted from http://openclipart.org/detail/3677/arrow-left-right-by-torfnase -->
<td><img class="noborder" src="images/green-double-arrow.png" height="500" alt="vertical green double arrow"></td>
<td class="top"> <br>High-level language<br> <br>Low-level language<br> <br>Assembly language<br> <br>Machine code</td>
</tr>
</table>
</section>
<section data-markdown><script type="text/template">
# Contents
[C++ Review](#/youshouldknowthis)
[Dynamic Memory Review](#/youshouldknowthistoo)
[C++ Inheritance](#/multinheritanceisfun)
[C++ Inheritance Problems](#/andithoughtpointerswerebad)
[C++11](#/becauseweneedthreemorepointertypes)
</script></section>
<section>
<section id="youshouldknowthis" data-markdown class="center"><script type="text/template">
# C++ Review
</script></section>
<section data-markdown><script type="text/template">
## Syntax
- \*
- pointer, when in a declaration statement
```
Rectangle *someRectangle;
```
- dereferences all other times
- Accesses the memory address held in the pointer variable
- &
- "reference" in a declaration
```
List & someList = someOtherList;
void printList(const List & theList);
```
- "address of"
```
Rectangle anotherRectangle;
someRectangle = &anotherRectangle;
```
</script></section>
<section data-markdown><script type="text/template">
## Pointer Variables are Typed
```
double Z = 26.0;
int * someInt = &Z;
```
- `someInt` is a pointer to an `int`
- `&Z` is the address of a `double`
- They don't match, so this will result in a compilation error:
```
cannot convert 'double*' to 'int*' in initialization
```
</script></section>
<section data-markdown><script type="text/template">
## Dereferencing: What's printed?
```
int n = 26;
int * somePointer = &n;
cout << somePointer << endl;
cout << *somePointer << endl;
```
</script></section>
<section data-markdown><script type="text/template">
## Dereferencing: What's printed?
```
int n = 26;
int * somePointer = &n;
*somePointer = 45;
cout << *somePointer << endl;
cout << n << endl;
```
</script></section>
<section data-markdown><script type="text/template">
## What's the Difference Between These?
```
ListNode * ptr1, * ptr2;
ptr1 = new ListNode;
ptr2 = new ListNode;
bool result1 = (ptr1 == ptr2);
bool result2 = (*ptr1 == *ptr2);
```
</script></section>
<section data-markdown><script type="text/template">
## References
```
int y = 5;
int &x = y;
```
- We can print the value 5 easily:
```
cout << x << endl;
```
- C++ automatically dereferences the reference
- How do we print the address in x?
```
cout << &x << endl;
```
- That's getting the address for a automatic dereference!
- How do we change the address of x?
</script></section>
<section data-markdown><script type="text/template">
## Pointer and Memory Allocation Pitfalls
- Uninitialized pointers
- Dereferencing `NULL` pointers
- Dangling pointer
- Losing address of dynamically allocated memory
</script></section>
<section data-markdown><script type="text/template">
## Pointers and Types
```
int main() {
Animal cow;
Animal* cowPtr1 = &cow;
Animal** cowPtr2(&cowPtr1);
Animal*** cowPtr3 = &cowPtr2;
}
```
What types are `cow`, `cowPtr1`, `cowPtr2`, and `cowPtr3`?
</script></section>
<section data-markdown><script type="text/template">
## Summary
| Variable name | Type of variable | Example emory address | Value stored |
|-|-|-|-|
| `cow` | `Animal` | 108 | 500 |
| `cowPtr1` | `Animal *` | 112 | 108 |
| `cowPtr2` | `Animal **` | 116 | 112 |
| `cowPtr3` | `Animal ***` | 120 | 116 |
</script></section>
<section data-markdown><script type="text/template">
## How Can We Change cow's Weight?
- Assume there is a setWeight(int weight) method
- via `cow`
- via `cowPtr1`
- via `cowPtr2`
- via `cowPtr3`
</script></section>
<section data-markdown><script type="text/template">
## The Tree code in Weiss
```
void insert (const Comparable &x, BinaryNode * & t)
```
- BinaryNode has a left and a right pointer
- What would happen if the second parameter was only a pointer
- As opposed to a reference to a pointer?
</script></section>
</section>
<section>
<section id="youshouldknowthistoo" data-markdown class="center"><script type="text/template">
# Dynamic Memory<br>Review
</script></section>
<section data-markdown><script type="text/template">
## For the upcoming examples...
- Is this code correct?
- Identify the problems in these code examples, if any...
</script></section>
<section data-markdown><script type="text/template">
##Example 1
```
void someFunc(int * somePointer) {
int someNode(3);
somePointer = &someNode;
}
int main() {
int * firstPointer;
// call someFunc
someFunc(firstPointer);
cout << *firstPointer << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Example 2
```
void someFunc() {
double *aliasPointer;
aliasPointer = new double(6.27);
cout << *aliasPointer << endl;
}
int main() {
double *somePointer;
double someVal(3.14);
somePointer = &someVal;
someFunc();
cout << *somePointer << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Example 3
```
int main() {
double duration = 3.14;
{
double * somePtr;
{
somePtr = &duration;
}
}
cout << *somePtr << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Example 4
```
int main() {
int * anotherPtr;
{
int someVal(8);
cout << *anotherPtr << endl;
anotherPtr = &someVal;
}
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Example 5
```
void someFunc(int *somePointer) {
int someVal(12);
{
int anotherVal(16);
somePointer = &anotherVal;
}
}
int main() {
int * yetAnotherPtr;
someFunc(yetAnotherPtr);
cout << *yetAnotherPtr << endl;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Example 6
```
int main() {
float * somePtr;
somePtr = new float(3.14);
cout << *somePtr << endl;
delete somePtr;
return 0;
}
```
</script></section>
<section data-markdown><script type="text/template">
## Example 7
```
void someFunc() {
int *aliasPtr;
aliasPtr = new int(25);
cout << *aliasPtr << endl;
}
int main() {
int * somePtr;
somePtr = new int(3);
someFunc();
cout << *somePtr << endl;
return 0;
}
```
</script></section>
</section>
<section>
<section id="multinheritanceisfun" data-markdown class="center"><script type="text/template">
# C++ Inheritance
</script></section>
<section data-markdown><script type="text/template">
## Inheritance
- Specifies hierarchical relationship between types
- You've seen this with Java; everything inherits, eventually, from `Object`
- (except `Object` itself, of course)
</script></section>
<section data-markdown><script type="text/template">
## Inheritance Example (Name)
Source code: [name-contact.cpp](code/09-advanced-cpp/name-contact.cpp.html) ([src](code/09-advanced-cpp/name-contact.cpp))
```
class Name {
public:
Name(void) : myName("") { }
~Name(void) { }
void SetName(string theName) {
myName = theName;
}
void print(void) {
cout << myName << endl;
}
private:
string myName;
};
```
</script></section>
<section data-markdown><script type="text/template">
## Inheritance Example (Contact)
Source code: [name-contact.cpp](code/09-advanced-cpp/name-contact.cpp.html) ([src](code/09-advanced-cpp/name-contact.cpp))
```
class Contact: public Name {
public:
Contact(void) {
myAddress = "";
}
~Contact(void) { }
void SetAddress(string theAddress) {
myAddress = theAddress;
}
void print(void) {
Name::print();
cout << myAddress << endl;
}
private:
string myAddress;
};
```
</script></section>
<section data-markdown><script type="text/template">
## Terminology
- Sub class (or derived class, or child class)
- Contact is the "child" class of Name
- Inherits:
- Data members defined in the parent class
- Member functions of the parent class
- Same initial data layout as the base class
- Can add:
- New data members, member functions, constructors, destructors
- Super class (or base class, or parent class)
- Name is the "parent" class of Contact
</script></section>
<section data-markdown><script type="text/template">
## Using this code
Source code: [name-contact.cpp](code/09-advanced-cpp/name-contact.cpp.html) ([src](code/09-advanced-cpp/name-contact.cpp))
```
int main(void) {
Contact c;
c.SetName("John Doe");
c.SetAddress("009 Olsson Hall");
c.print();
}
```
</script></section>
<section data-markdown><script type="text/template">
## Creating a Derived Class
- Space is allocated (on the stack or the heap) for the full object
- Enough space to store the data members inherited from the base class plus the data members defined in the derived class itself
- The base class's constructor is called to initialize the data members inherited from the base class
- The derived class's constructor is then called to initialize the data members added in the derived class
</script></section>
<section data-markdown><script type="text/template">
## Destructing a Derived Class
- Derived class's destructor called
- Base class's destructor called
- (i.e. in the reverse order than the constructors were called)
</script></section>
<section data-markdown><script type="text/template">
## Problems with single inheritance
Single inheritance has problems:
```
void insert (const Comparable &x, BinaryNode * & t)
```
- What if the parameter `x`, the element to be inserted, is a non-primitive type:
- Sphere (which should inherit from a Shape)
- BigInteger (which could inherit from BigNumber)
- Etc.
- What if it also needs to be Serializable?
</script></section>
<section data-markdown><script type="text/template">
## C++ has *multiple* inheritance
```
class Sphere : public Shape, public Comparable,
public Serializable {
// ...
};
```
Sphere now has all the methods and fields in Shape, Comparable *and* Serializable
</script></section>
<section data-markdown><script type="text/template">
## C++ vs. Java
- But wait, you say -- we've seen this before:
```
public class Sphere extends Shape implements Comparable,
Serializable {
```
- Java can *fake* multiple inheritance through interfaces
- It's actually allowing type-substitution for multiple classes that implement an interface
</script></section>
<section data-markdown><script type="text/template">
## Static vs. Dynamic Dispatch
- Static
- Decision on which member function to invoke made using *compile-time* type of an object
- Dynamic
- Decision on which member function to invoke made using *run-time* type of an object
</script></section>
<section data-markdown><script type="text/template">
## Example
```
class Person {
public:
// ...
void print(ostream &out = cout);
// ...
};
class Student : public Person {
public:
// ...
void print(ostream &out = cout);
// ...
};
```
</script></section>
<section data-markdown><script type="text/template">
## Static Dispatch Examples
```
Person *p;
if ( user_input )
p = new Student();
else
p = new Person();
p->print();
```
```
Student s(123456789, "Jane", 4.0);
Person &p = s;
s.print(); // Student::print()
p.print(); // Person::print()
```
</script></section>
<section data-markdown><script type="text/template">
## Dynamic Dispatch
- Incurs runtime overhead
- Program must maintain extra information
- Compiler must generate code to determine which member function to invoke
- Syntax in C++
- `virtual` keyword
- Java does this by default, BTW
- i.e. everything is virtual
</script></section>
<section data-markdown><script type="text/template">
## Dynamic Dispatch
```
class Person {
public:
// ...
virtual void print(ostream &out = cout);
// ...
};
```
Should also be used for the base class destructor
</script></section>
<section>
<h2>Background: virtual method tables</h2>
<table class="transparent"><tr><td class="top"><pre><code>class A {
virtual void foo()
{ ... }
}
class B : public A {
virtual void foo()
{ ... }
}</code></pre></td><td class="top"><pre><code>void main () {
int which = rand() % 2;
A *bar;
if ( which )
bar = new A();
else
bar = new B();
bar->foo();
return 0;
}</code></pre></td></tr></table>
<ul>
<li>Which <code>foo()</code> is called?</li>
<li>It's not known until run-time!</li>
</ul>
</section>
<section data-markdown><script type="text/template">
## Virtual method tables
- Each object contains a pointer to the virtual method table
- In addition to any other fields
- That table has the addresses of the methods
- Any virtual method must follow the pointer to the object... (one pointer dereference)
- Then follow the virtual method table pointer... (second pointer dereference)
- Then lookup the method pointer
- Then jump to that method (third pointer dereference)
</script></section>
<section>
<h2>Virtual method table example</h2>
<table class="transparent"><tr><td class="top">
<ul>
<li>In main():
<pre><code>Person *p = new Student();</code></pre></li>
<li class="fragment" data-fragment-index="1">First the Person constructor is called...<ul>
<li class="fragment" data-fragment-index="2">And creates a regular Person object...</li>
<li class="fragment" data-fragment-index="4">Then sets up the virtual method table (VMT)...</li></ul></li>
<li class="fragment" data-fragment-index="6">Then the Student constructor is called...<ul>
<li class="fragment" data-fragment-index="7">And updates the object...</li>
<li class="fragment" data-fragment-index="9">Then updates the VMT...</li></ul></li>
</ul>
</td><td style="width:20px"></td><td class="top">
<img src="images/spacer.gif" width="388" height="1" alt="spacer" class="plain">
<img class="fragment" src="images/09-advanced-cpp/vmt-1.svg" alt="virtual method table image 1" style="position:absolute" data-fragment-index="3">
<img class="fragment" src="images/09-advanced-cpp/vmt-2.svg" alt="virtual method table image 2" style="position:absolute" data-fragment-index="5">
<img class="fragment" src="images/09-advanced-cpp/vmt-3.svg" alt="virtual method table image 3" style="position:absolute" data-fragment-index="8">
<img class="fragment" src="images/09-advanced-cpp/vmt-4.svg" alt="virtual method table image 4" style="position:absolute" data-fragment-index="10">
</td></tr></table>
</section>
<section data-markdown><script type="text/template">
## More on virtual method tables
- When creating a subclass object, the constructor of each subclass overwrites the appropriate pointers in the virtual method table with the overridden method pointers
- Hence why the run-time lookup will work properly
- Also see the [Wikipedia article on virtual method tables](http://en.wikipedia.org/wiki/Virtual_method_table)
</script></section>
<section data-markdown><script type="text/template">
## Abstract classes
Consider:
```
class shape {
public:
virtual void draw() = 0;
};
```
- Must be virtual!
- `draw()` is called a "pure virtual function" or "pure virtual method"
- It has no body definition in the .cpp file
- And thus this class can not be instantiated, since there is no method body
- Sub-classes (circle, triangle, etc.) would define their own method bodies
</script></section>
<section data-markdown><script type="text/template">
## More on abstract classes
- This is the equivalent of abstract classes in Java
- If you make a class that has all pure virtual methods, then it effectively acts like a Java interface
- Note that a subclass does not need to define the method body...
- ... unless it wants to be able to be instantiated,
as a class can only be instantiated into an object if ALL the methods have defined bodies
</script></section>
</section>
<section>
<section id="andithoughtpointerswerebad" data-markdown class="center"><script type="text/template">
# C++ Inheritance Problems
</script></section>
<section data-markdown><script type="text/template">
## Problems with Inheritance
What sort of problems can this cause?
```
class A {
private: int bar;
public: void foo() { bar = 7; }
};
class B {
private: int bar;
public: void foo() { bar = 1; }
};
class C: public A, public B {
// which foo() is inherited? Which bar?
// if C sets bar to something, which one?
// Does B's foo() and C's foo() use the same bar?
// Difficulty in layout memory
};
```
</script></section>
<section data-markdown><script type="text/template">
## Semantic Ambiguities
What if the relationship below occurs?
![multiple inheritance diagram](images/09-advanced-cpp/multiple-inheritance.svg)
- This shows both *replicated* and *shared* multiple inheritance
- As one of the ancestors (gp_list_node) is replicated and one is shared (person) in the parent classes of student_prof
</script></section>
<section data-markdown><script type="text/template">
## Shared vs repliated multiple inheritance
- In C++, replicated is the default
- Shared inheritance can be specified by using the keyword `virtual`:
```
class student: public virtual person,
public gp_list_node { ... };
class professor: public virtual person,
public gp_list_node { ... };
class student_prof: public virtual professor,
public virtual student { ... };
```
</script></section>
<section data-markdown><script type="text/template">
## Types of multiple inheritance
There are four types:
1. Shared
- What Person is in the diagram on the previous slide
2. Replicated (or repeated)
- What gp_list_node is in the diagram on the previous slide
3. Non-replicated (or non-repeated)
- A language that does not allow shared or replicated (i.e. no common ancestors allowed)
4. Mix-in
- What Java (and others) use to fake multiple inheritance through the use of interfaces
</script></section>
<section data-markdown><script type="text/template">
## What will this Java code do?
```
class Fruit {
static void addFruit (Fruit basket[])
{ basket[0] = new Apple(); }
public String toString() { return "I am a Fruit"; }
}
class Apple extends Fruit {
public String toString() { return "I am an Apple"; }
}
class Orange extends Fruit {
public String toString() { return "I am an Orange"; }
}
public class Covariant {
public static void main (String[] args) {
Orange oranges[] = { new Orange(), new Orange(),
new Orange() };
Fruit.addFruit(oranges);
for ( int i = 0; i < 3; i++ )
System.out.println (oranges[i]);
}
}
```
</script></section>
<section data-markdown><script type="text/template">
## Covariant arrays: a simpler version
From [Wikipedia](http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29)
```
// a is a single-element array of String
String[] a = new String[1];
// b is an array of Object
Object[] b = a;
// Assign an Integer to b. This would be possible if b
// really were an array of Object, but since it really
// is an array of String, we will get a
// java.lang.ArrayStoreException.
b[0] = new Integer (1);
```
</script></section>
</section>
<section>
<section id="becauseweneedthreemorepointertypes" data-markdown class="center"><script type="text/template">
# C++11
</script></section>
<section data-markdown><script type="text/template">
## C++11
- The new standard, agreed to in August 2011
- It was called C++0x because it was expected to be approved before 2010...
- It adds to the current C++ version (C++03), while not modifying the older version (much)
- We will review some of the changes...
</script></section>
<section data-markdown><script type="text/template">
## Move constructors
- Consider assigning to a global vector `x` from a local vector `y`
- And knowing that vector `y` is going out of scope
- Recall that both `x` and `y` point to an array holding the values
- You could perform a deep copy...
- ... or just have `x`'s array pointer point to y's array
- And don't delete `y`'s array when it goes out of scope
- This prevents necessitating a deep copy
</script></section>
<section>
<h2>Uniform initialization</h2>
<table class="transparent"><tr><td class="top"><pre><code>class Timer {
public:
Timer();
};
class TimeKeeper {
public:
TimeKeeper(const Timer& t);
int get_time();
};
int main() {
// Look at the 'Timer()' in
// the next line...
TimeKeeper time_keeper(Timer());
return time_keeper.get_time();
}</code></pre></td><td class="top">
<ul>
<li>Is the indicated part:</li>
</ul>
<ol>
<li>A variable definition for <code>time_keeper</code> that takes in a constructed Timer object</li>
<li>A <code>time_keeper</code> function that takes in a function as a parameter?</li>
</ol>
<ul>
<li>Most people want the first; the compiler insists on the second</li>
</ul></td></tr></table>
</section>
<section data-transition="fade" data-transition-speed="fast">
<h2>Uniform initialization</h2>
<table class="transparent"><tr><td class="top"><pre><code>class Timer {
public:
Timer();
};
class TimeKeeper {
public:
TimeKeeper(const Timer& t);
int get_time();
};
int main() {
// Look at the 'Timer()' in
// the next line...
TimeKeeper time_keeper(Timer());
return time_keeper.get_time();
}</code></pre></td><td class="top">
<ul>
<li>The new standard will use curly-brackets for both constructor calls and initialization lists (e.g., arrays)<br> </li>
<li>So we use the following:</li>
</ul>
<pre><code>TimeKeeper
time_keeper
{Timer()};
</code></pre>
</td></tr></table>
</section>
<section data-markdown><script type="text/template">
## Range-based for loops
```
int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array) {
x *= 2;
}
```
Just like in Java
</script></section>
<section data-markdown><script type="text/template">
## New (but optional) function/method syntax
```
struct SomeStruct {
auto func_name(int x, int y) -> int;
};
auto SomeStruct::func_name(int x, int y) -> int {
return x + y;
}
```
- Note the trailing return type
- This resolves problems when you are adding lots of C++ qualifiers
</script></section>
<section data-markdown><script type="text/template">
## New NULL!
- NULL for pointers was really zero
- And type-checking was hard, since you are type checking a pointer against an int
- Now there is `nullptr`
- Which type checks better with pointers
</script></section>
<section data-markdown><script type="text/template">
## Smart pointers
- They are different than regular points or references
- Like regular pointers, but they include memory management algorithms as well
- `auto_ptr` indicates that the caller must deallocate it
- `unique_ptr` forces only one pointer to point to that object (the "old" one points to nullptr)
- `shared_ptr` does reference counting, and will be deallocated (by the compiler) when nobody points to it anymore
- `weak_ptr` is like shared_ptr, but does not modify the reference count; used to handle circular references and reference counting
</script></section>
<section data-markdown><script type="text/template">
## Other improvements
- Better handling of multitasking and threads
- New type of `long long int` that is *guaranteed* to be at least 64 bits
- Most compilers support this already
- Static assertions for debugging
- Better hash tables in STL
</script></section>
<section data-markdown><script type="text/template">
## What all this means
- Modern C++ code is very complicated, and very difficult for us to understand easily
- And it makes a single C++ course insufficient to understand the level of C++ used in the industry...
</script></section>
<section data-markdown><script type="text/template">
## How to use these features
- All modern compilers support C++11 features (well, mostly...)
- This includes the course submission server
- To use these features, you have to pass the `-std=c++11` flag to the compiler
- Put it in the Makefile!
</script></section>
</section>
</div>
</div>
<script src='../slides/reveal.js/dist/reveal.js'></script><script src='../slides/reveal.js/plugin/zoom/zoom.js'></script><script src='../slides/reveal.js/plugin/notes/notes.js'></script><script src='../slides/reveal.js/plugin/search/search.js'></script><script src='../slides/reveal.js/plugin/markdown/markdown.js'></script><script src='../slides/reveal.js/plugin/highlight/highlight.js'></script><script src='../slides/reveal.js/plugin/math/math.js'></script>
<script src="js/settings.js"></script>
</body>
</html>