computer science introduction to...

Post on 26-Jun-2020

4 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction to C++

Haysn Hornbeck

Computer Science

Housekeeping

Online Survey

What do you use?

How skilled are you?

What are you interested in?

2

https://goo.gl/forms/pyipArU6IG4gUgxu1

Housekeeping

Introductory Courses

● Quick introductions● Refresh knowledge● Tease full courses?

3

https://goo.gl/forms/pyipArU6IG4gUgxu1

Housekeeping

● Intro to Linux● Advanced Linux● Intro to C++● Code Repositories● Pointers and Indirection● Designing OO Programs● Debugging in Eclipse● Memory management

4https://moodle.cpsc.ucalgary.ca/

https://goo.gl/forms/pyipArU6IG4gUgxu1

Housekeeping

Materials (CompSci)

● UofC IT account(see HelpDesk)

● Remote Loginhttp://www.ucalgary.ca/cpsc/tech/services/remote_access_samba

5

https://goo.gl/forms/pyipArU6IG4gUgxu1

Housekeeping

Materials(not CompSci)

● Mac OS XLibraries, Various odd places

● Bootable USB keyshttps://rufus.akeo.ie/http://unetbootin.github.io/

● Virtual Machineshttps://virtualboxes.org/images/

6

https://goo.gl/forms/pyipArU6IG4gUgxu1

Housekeeping

Online Survey

7

https://goo.gl/forms/pyipArU6IG4gUgxu1

HistoryC

8

History

1966

BCPL

9https://www.bell-labs.com/usr/dmr/www/bcpl.pdf

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)

10

https://en.wikipedia.org/wiki/BCPL#Examples

BCPL

• First to use code blocks• Two-step compilation• Procedures with parameters and return• Only one data type, 16-bit word• Pointers

11

History

1969

B

12

B

13https://www.bell-labs.com/usr/dmr/www/kbman.html

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);}

History

1972

Unix on the PDP-11

14

History

1972

C

15

C

16

#include <stdio.h>

int fact( n ) {

if (n<2)return 1;

elsereturn n * fact(n-1);

}

int main( int argc, char* argv[] ) {

int i = 1;

while (i<6)printf( “%f\n”, fact(i++) );

return 0;}

C

• Multiple fundamental data types• Structures• Static types, weak enforcement• Weak array support• Multi-step compilation

17

Multiple Data Types

bool

char

short

int

long

long long

18

unsigned char

unsigned short

unsigned int

unsigned long

unsigned long long

float

double

Structures

19

// by tagname

struct point {

float x;float y;

};

struct point p;

// by alias

typedef struct {

float x;float y;

} point;

point p;// tagname → aliastypedef struct point d2;

d2 p;

Static Types, Weak Enforcement

20

// 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*)&pi;

Static Types, Weak Enforcement

21

// 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*)&pi; // 1078530011 ?!

Weak Array Support

22

int array[5];

for (int it = 0; it < 11; it++)array[it] = it; // this works?!

Weak Array Support

23

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 150 char** argv int argc

16 Array[0] Array[1] Array[2] Array[3]32 Array[4 ] float pi48 int fifth int fourth char third int second64 long first

Multi-step Compilation

24

Preprocessor(insert files, expand macros)

Compile(convert to assembly code)

Assemble(convert to machine code)

Link(combine parts and libraries)

Preprocessor

25

main.cpp

shared.h stdio.h

main.cpp

shared.h

stdio.h

Compile

26

main.cpp

shared.h

stdio.h

main.asm

Assembly Language

27

.file "test.c" .text .globl main .type main, @functionmain:.LFB0: .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.L3: movl -4(%rbp), %eax cltq movl -4(%rbp), %edx movl %edx, -64(%rbp,%rax,4) addl $1, -4(%rbp)

.L2: cmpl $10, -4(%rbp) jle .L3 movl $0, %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc.LFE0: .size main, .-main .section .rodata .align 4.LC0: .long 1078530011 .ident "GCC: (Debian 6.2.1-5) 6.2.1 20161124" .section .note.GNU-stack,"",@progbits

main.asm

Assemble

28

main.bin

Link

29

main.bin

stdio.bin

processing.bin

main.bin

stdio.bin

processing.bin

Why C Stinks

● Poor organization● Side effects galore● “Trust the coder”

● Pointers

30

History

1967

Simula 67

31

Simula 67

32

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

1979

C with Classes

33

History

1983

C++

34

History

1989

C++ 2.0

35

History

1998

ISO/IEC 14882:1998(C++98)

36

History

37

1998 2003

2011 2014

2017

Demo Code

38

Demo Code

39

√(x−xo)2+( y−yo)

2= r

π =circumference

diameter

Demo Code

40

|x−xo|+|y− yo| = r

π =circumference

diameter

Demo Code

41

|x−xo|+|y− yo| = r

π = 4

Demo Code

42

3√(x−xo)3+( y− yo)

3 = r

π ≈ 3.259767993

Demo Code

43

p√(x−xo)p+( y− yo)

p = r

π = ?

https://en.wikipedia.org/wiki/Lp_space#The_p-norm_in_finite_dimensions

Classes, Attributes, Methods, ...

44

class PiEstimator {

private: CircleGenerator cg; // used to create points set<Point> points; // the points that make up our arc

public: PiEstimator( fp p );

fp getP() { return cg.getP(); } void setP( fp p );

// estimate Pi via a lot of "random" points fp estimateViaFlood( ulong count );

// estimate Pi via distance segmentation fp estimateViaSegment( fp maxDist );

}; // PiEstimator

Typedef

45

typedef unsigned long ulong;

typedef double fp;

Inheritence, Virtual Functions

46

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

47

class Point {

private: fp x; // the coordinates of this point in 2D space fp y;

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

Operator Overloading

48

class Point {

private: fp x; // the coordinates of this point in 2D space fp y;

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();

}; // PointPoint a;Point b;

Point c = a – b; // Point c( a.getX() - b.getX(), a.getY() - b.getY() );

Inheritence, Virtual Functions

49

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

50

#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

51

#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

52

#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

53

// creating a namespacenamespace myPackage {

class myClass {

public:void doSomething();

};

}

// “importing” from a namespace

using myPackage::myClass;

myClass.doSomething();

Namespaces

54

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

55

class PairPoints {

private:

Point a;Point b;

public:

Point first() { return a; }Point second() { return b; }

};

Templates

56

template <class T>;class Pair {

private:

T a;T b;

public:

T first() { return a; }T second() { return b; }

};

Pair<Point> ray;

Template Specialization

57

template <class T>;class Pair {

// assume it’s a pass-by-valuebool lessThan( const& T rhs ) { return *this < rhs; }

// ...

template <>;class Pair<T*> {

// know we have a referencebool lessThan( const& T rhs ) { return **this < *rhs; }

// ...

Standard Template Library

58

Vector

List

Set

Map

Queue

Array

- Dynamic array

- Linked list

- Ordered list

- Key -> value

- First in, First out

- Fixed-size array

Operator Overloading

59

class Point {

private: fp x; // the coordinates of this point in 2D space fp y;

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

Memory Management

60

// CPoint* 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...

C++ = Cwith some added syntactic sugar

61

C++ = C

● All C operators work

● “main” function still around

● Ditto pointers

● Preprocessor and garbage dependency handling

● Compile-time enforcement

● Permissive casting

62

C++ = C

30+ years of development● More libraries than any other language

● Interfaces to other languages

● Ported everywhere

● The Boost libraries

63

64

LabChallenges

http://pages.cpsc.ucalgary.ca/~hhornbec/moodle/cpp_intro/

65

G++

(GNU C compiler)

http://pages.cpsc.ucalgary.ca/~hhornbec/moodle/cpp_intro/

-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.

top related