Computer Science Introduction to C++ Haysn Hornbeck
Housekeeping Online Survey What do you use? How skilled are you? What are you interested in? https://goo.gl/forms/pyiparu6ig4gugxu1 2
Housekeeping Introductory Courses Quick introductions Refresh knowledge Tease full courses? https://goo.gl/forms/pyiparu6ig4gugxu1 3
Housekeeping Intro to Linux Advanced Linux Intro to C++ Code Repositories Pointers and Indirection Designing OO Programs Debugging in Eclipse Memory management https://goo.gl/forms/pyiparu6ig4gugxu1 https://moodle.cpsc.ucalgary.ca/ 4
Housekeeping Materials (CompSci) UofC IT account (see HelpDesk) Remote Login http://www.ucalgary.ca/cpsc/tech/services/remote_access_samba https://goo.gl/forms/pyiparu6ig4gugxu1 5
Housekeeping Materials (not CompSci) Mac OS X Libraries, Various odd places Bootable USB keys https://rufus.akeo.ie/ http://unetbootin.github.io/ Virtual Machines https://virtualboxes.org/images/ https://goo.gl/forms/pyiparu6ig4gugxu1 6
Housekeeping Online Survey https://goo.gl/forms/pyiparu6ig4gugxu1 7
History C 8
History 1966 BCPL https://www.bell-labs.com/usr/dmr/www/bcpl.pdf 9
BCPL GET "LIBHDR" // calculate factorials LET START() = VALOF $( FOR I = 1 TO 5 DO WRITEF("%N! = %I4*N", I, FACT(I)) RESULTIS 0 $) AND FACT(N) = N = 0 -> 1, N * FACT(N - 1) https://en.wikipedia.org/wiki/bcpl#examples 1 0
BCPL 1 1 First to use code blocks Two-step compilation Procedures with parameters and return Only one data type, 16-bit word Pointers
History 1 2 1969 B
B main() { extrn fact, printn, putchar; auto i, r; } i = 1; while(i<6) { printn( fact(i), 10 ); putchar( *n ); /* *n = newline */ i =+ 1; } printn(n,b) { extrn putchar; auto a; } if(a=n/b) /* assign and check */ printn(a, b); putchar(n%b + '0'); /* exploit ASCII encoding */ fact(n) { } if(n<2) return 1; else return n * fact(n-1); https://www.bell-labs.com/usr/dmr/www/kbman.html 1 3
History 1 4 1972 Unix on the PDP-11
History 1 5 1972 C
C 1 6 #include <stdio.h> int fact( n ) { } if (n<2) return 1; else return n * fact(n-1); int main( int argc, char* argv[] ) { int i = 1; while (i<6) printf( %f\n, fact(i++) ); } return 0;
C 1 7 Multiple fundamental data types Structures Static types, weak enforcement Weak array support Multi-step compilation
Multiple Data Types 1 8 bool char short int long long long unsigned char unsigned short unsigned int unsigned long unsigned long long float double
Structures // by tagname struct point { }; float x; float y; struct point p; // tagname alias typedef struct point d2; // by alias typedef struct { float x; float y; } point; point p; d2 p; 1 9
Static Types, Weak Enforcement 2 0 // all these are valid long first = 17592186044416; int second = 16777216; char third = first + second; int fourth = 4.0134; float pi = 3.14159274; int fifth = *(int*)π
Static Types, Weak Enforcement 2 1 // all these are valid long first = 17592186044416; int second = 16777216; char third = first + second; // 0 int fourth = 4.0134; // 4 float pi = 3.14159274; int fifth = *(int*)π // 1078530011?!
Weak Array Support 2 2 int array[5]; for (int it = 0; it < 11; it++) array[it] = it; // this works?!
Weak Array Support 2 3 int array[5]; for (int it = 0; it < 11; it++) array[it] = it; // this works?! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 char** argv int argc 16 Arra y[0] Array[1] Array[2] Arra y[3] 32 Arra y[4 ] float pi 4 8 int fifth int fourth char third int second 64 long first
Multi-step Compilation Preprocessor (insert files, expand macros) Compile (convert to assembly code) Assemble (convert to machine code) Link (combine parts and libraries) 2 4
Preprocessor 2 5 shared.h stdio.h stdio.h shared.h main.cpp main.cpp
Compile 2 6 stdio.h shared.h main.asm main.cpp
Assembly Language main:.lfb0:.l3:.file "test.c".text.globl main.type main, @function.cfi_startproc pushq %rbp.cfi_def_cfa_offset 16.cfi_offset 6, -16 movq %rsp, %rbp.cfi_def_cfa_register 6 movl %edi, -68(%rbp) movq %rsi, -80(%rbp) movabsq $17592186044416, %rax movq %rax, -16(%rbp) movl $16777216, -20(%rbp) movl -20(%rbp), %eax movl %eax, %edx movq -16(%rbp), %rax addl %edx, %eax movb %al, -21(%rbp) movl $4, -28(%rbp) movss.lc0(%rip), %xmm0 movss %xmm0, -36(%rbp) leaq -36(%rbp), %rax movl (%rax), %eax movl %eax, -32(%rbp) movl $0, -4(%rbp) jmp.l2 movl cltq movl movl addl -4(%rbp), %eax -4(%rbp), %edx %edx, -64(%rbp,%rax,4) $1, -4(%rbp).L2:.LFE0:.LC0: cmpl $10, -4(%rbp) jle.l3 movl $0, %eax popq %rbp.cfi_def_cfa 7, 8 ret.cfi_endproc.size main,.-main.section.rodata.align 4.long 1078530011.ident "GCC: (Debian 6.2.1-5) 6.2.1 20161124".section.note.GNU-stack,"",@progbits 2 7
Assemble 2 8 main.asm main.bin
Link 2 9 stdio.bin stdio.bin main.bin main.bin processing.bin processing.bin
Why C Stinks Pointers 3 0 Poor organization Side effects galore Trust the coder
History 3 1 1967 Simula 67
Simula 67 3 2 Class Rectangle (Width, Height); Real Width, Height;! Class with two parameters; Begin Real Area, Perimeter;! Attributes; Procedure Update;! Methods (Can be Virtual); Begin Area := Width * Height; Perimeter := 2*(Width + Height) End of Update; Boolean Procedure IsSquare; IsSquare := Width=Height; Update;! Life of rectangle started at creation; OutText("Rectangle created: "); OutFix(Width,2,6); OutFix(Height,2,6); OutImage End of Rectangle;
History 3 3 1979 C with Classes
History 3 4 1983 C++
History 3 5 1989 C++ 2.0
History 3 6 1998 ISO/IEC 14882:1998 (C++98)
History 3 7 1998 2003 2011 2014 2017
Demo Code 3 8
Demo Code 3 9 (x x o ) 2 +( y y o ) 2 = r π = circumference diameter
Demo Code 4 0 x x o + y y o = r π = circumference diameter
Demo Code 4 1 x x o + y y o = r π = 4
Demo Code 4 2 3 (x x o ) 3 +( y y o ) 3 = r π 3.259767993
Demo Code 4 3 https://en.wikipedia.org/wiki/lp_space#the_p-norm_in_finite_dimensions p (x x o ) p +( y y o ) p = r π =?
Classes, Attributes, Methods,... 4 4 class PiEstimator { private: CircleGenerator cg; set<point> points; public: PiEstimator( fp p ); fp getp() { return cg.getp(); } void setp( fp p ); // used to create points // the points that make up our arc // estimate Pi via a lot of "random" points fp estimateviaflood( ulong count ); // estimate Pi via distance segmentation fp estimateviasegment( fp maxdist ); }; // PiEstimator
Typedef 4 5 typedef unsigned long ulong; typedef double fp;
Inheritence, Virtual Functions 4 6 class DistanceMetric { public: static virtual fp distance( const& Point, const& Point ); }; // DistanceMetric class EuclideanDistance : public DistanceMetric { public: static fp distance( const& Point a, const& Point b ) { }; } return sqrt( (a.getx() - b.getx())*(a.getx() - b.getx()) + (a.gety() - b.gety())*(a.gety() - b.gety()) );
Operator Overloading 4 7 class Point { private: fp x; fp y; public: /*... */ // the coordinates of this point in 2D space // so we're organized in set bool operator<( const Point& a ) const; // to make some operations easier Point operator+( const Point& a ) const; Point operator-( const Point& a ) const; Point operator*( const fp& a ); Point power( const fp& a ); Point absolute(); }; // Point
Operator Overloading class Point { private: fp x; fp y; // the coordinates of this point in 2D space public: /*... */ // so we're organized in set bool operator<( const Point& a ) const; // to make some operations easier Point operator+( const Point& a ) const; Point operator-( const Point& a ) const; Point operator*( const fp& a ); Point power( const fp& a ); Point absolute(); }; // Point Point a; Point b; Point c = a b; // Point c( a.getx() - b.getx(), a.gety() - b.gety() ); 4 8
Inheritence, Virtual Functions 4 9 class DistanceMetric { public: static virtual fp distance( const& Point, const& Point ); }; // DistanceMetric class EuclideanDistance : public DistanceMetric { public: static fp distance( const& Point a, const& Point b ) { // return sqrt( (a.getx() - b.getx())*(a.getx() - b.getx()) + // (a.gety() - b.gety())*(a.gety() - b.gety()) ); }; } return ((a b).dot(a b)).sqrt();
Input / Output 5 0 #include <stdio.h> printf( For precision %f and exponent %f, Pi ~= %.15f\n, precision, exponent, pe.estimateviasegment( precision ) ); using std::cout; using std::endl; using std::setprecision; #include <iostream> std::cout << "For precision " << precision << " and exponent " << exponent << ", Pi ~= " << std::setprecision(15) << pe.estimateviasegment( precision ) << std::endl;
Namespaces 5 1 #include <stdio.h> printf( For precision %f and exponent %f, Pi ~= %.15f\n, precision, exponent, pe.estimateviasegment( precision ) ); #include <iostream> using std::cout; using std::endl; using std::setprecision; cout << "For precision " << precision << " and exponent " << exponent << ", Pi ~= " << setprecision(15) << pe.estimateviasegment( precision ) << endl;
Namespaces 5 2 #include <stdio.h> printf( For precision %f and exponent %f, Pi ~= %.15f\n, precision, exponent, pe.estimateviasegment( precision ) ); #include <iostream> using std::cout; using std::endl; using std::setprecision; cout << "For precision " << precision << " and exponent " << exponent << ", Pi ~= " << setprecision(15) << pe.estimateviasegment( precision ) << endl; // Point Point::operator+( const Point& a ) const;
Namespaces 5 3 // creating a namespace namespace mypackage { class myclass { public: void dosomething(); }; } // importing from a namespace using mypackage::myclass; myclass.dosomething();
Namespaces 5 4 Point Point::pow( const fp& s ) { // doesn t compile } return Point( pow(x,s), pow(y,s) ); Point Point::power( const fp& s ) { } return Point( pow(x,s), pow(y,s) );
Templates 5 5 class PairPoints { private: Point a; Point b; public: Point first() { return a; } Point second() { return b; } };
Templates 5 6 template <class T>; class Pair { private: T a; T b; public: T first() { return a; } T second() { return b; } }; Pair<Point> ray;
Template Specialization 5 7 template <class T>; class Pair { // assume it s a pass-by-value bool lessthan( const& T rhs ) { return *this < rhs; } //... template <>; class Pair<T*> { // know we have a reference bool lessthan( const& T rhs ) { return **this < *rhs; } //...
Standard Template Library 5 8 Vector - Dynamic array List Set Map Queue Array - Linked list - Ordered list - Key -> value - First in, First out - Fixed-size array
Operator Overloading 5 9 class Point { private: fp x; fp y; public: /*... */ // the coordinates of this point in 2D space // so we're organized in set bool operator<( const Point& a ) const; // to make some operations easier Point operator+( const Point& a ) const; Point operator-( const Point& a ) const; Point operator*( const fp& a ); Point power( const fp& a ); Point absolute(); }; // Point
Memory Management 6 0 // C Point* point = (Point*) malloc( sizeof(point) ); Point* array = (Point*) malloc( sizeof(point) * count ); free(point); free(array); // C++ Point* point = new Point(); Point* array = new Point[3]; std::vector<point> better; delete point; delete[] array; // quite important!
But... 6 1 C++ = C with some added syntactic sugar
C++ = C 6 2 All C operators work main function still around Ditto pointers Preprocessor and garbage dependency handling Compile-time enforcement Permissive casting
C++ = C 6 3 30+ years of development More libraries than any other language Interfaces to other languages Ported everywhere The Boost libraries
6 4 Lab Challenges http://pages.cpsc.ucalgary.ca/~hhornbec/moodle/cpp_intro/
G++ (GNU C compiler) -o [file] -g -ggdb -O[number] -I [directory] -l [file] The file to output to. Add debugging symbols. Add debugging symbols for GDB. Optimize the code, to varying levels. [0-3] Search for header files in this directory, too. Link in this library, too. http://pages.cpsc.ucalgary.ca/~hhornbec/moodle/cpp_intro/ 6 5