A C++ Crash Course Part I

download A C++ Crash Course Part I

of 57

  • date post

    02-Jan-2016
  • Category

    Documents

  • view

    16
  • download

    3

Embed Size (px)

description

A C++ Crash Course Part I. UW Association for Computing Machinery http://www.cs.washington.edu/orgs/acm/tutorials acm@cs.washington.edu. Questions & Feedback to Hannah C. Tang (hctang) and Albert J. Wong (awong). C/C++ fundamentals Functions Primitive data types The stack - PowerPoint PPT Presentation

Transcript of A C++ Crash Course Part I

  • A C++ Crash CoursePart IUW Association for Computing Machinery http://www.cs.washington.edu/orgs/acm/tutorialsacm@cs.washington.eduQuestions & Feedback to Hannah C. Tang (hctang) and Albert J. Wong (awong)

  • What Well CoverC/C++ fundamentalsFunctionsPrimitive data types

    The stack Arrays (working model)Pointers

    A practice program

    C-style typesTypedefsStructs

    Arrays (whole story)

    More C++-ismsC++-style vs Java-style referencesC++ gotchas

  • What Were NOT CoveringTopics related to C++ classesMultiple filesThe preprocessor

    C++ classesInheritance and dynamic dispatch

    Memory managementThe heapDestructors

    Advanced topicsModifiers: const, static, and externOperator overloadingTemplates

  • Goals of JavaJavaSimpleConsistentHuge OO FocusCross platform via a virtual machineOriginally for embedded systems

    Java, C, and C++, have different design goals.

  • Goals of C and C++CLow levelNo Runtime Type infoEasy implementation

    C++Originally to add some OO functionality to CAttempt to be a higher-level languageNow its a totally different language

    C and C++ are popular because they have met, with reasonable success, their goals.

  • A simple program snippetpublic void printSum(void){ int x, y;

    // get user input

    int sum = x + y;

    // print sum }void printSum(void){ int x, y;

    // get user input

    int sum = x + y;

    // print sum }

  • The simple program Java versionclass Calculator { public void printSum(void) { int x, y;

    // get user input

    int sum = x + y;

    // print sum }}

    class App { public static void main(String[] args) { Calculator c = new Calculator; c.printSum(); }}AppCalculator

  • The simple program C++ versionvoid printSum(void) { int x, y;

    // get user input

    int sum = x + y;

    // print sum }

    int main(int argc, const char * argv[]) { printSum(); return 0;}class Calculator { public void printSum(void) { int x, y;

    // get user input

    int sum = x + y;

    // print sum }}

    class App { public static void main(String[] args) { Calculator c = new Calculator; c.printSum(); }}

  • Procedural ProgrammingFunctions are free-floating methods disassociated from any class

    Functions declarations can be separate from function implementationsThe declaration provides the signature, which specifies the name, return type, and parameter list of the function

    C is completely procedural

    C++ mixes object-oriented and procedural programming

  • Discussion Point IHelloWorldA traffic simulator Must simulate cars, roads, and the interactions between these entitiesA calculator Accepts two numbers, then calculates the sum or difference, depending on a user-selected operatorAn mp3 player Accepts a list of files, and plays them in the specified order. Needs to support skinsCome up with your own exampleWhich of these programs can be written procedurally? Object-orientedly?

  • Function Syntax and Semantics can be any type except an arrayClass-scoped methods and free-floating functions are basically the same, except functionName( ); int calculatePower(int base, int exponent);

  • Parameter Passing in Java Part Iclass Example {

    public void moveToDiagonal(Point p) { p.setY(p.getX()); }

    public static void main( String[] args ) { Point pt; pt = new Point(3, 4); moveToDiagonal(pt); // What are the coordinates of pt now? }}

  • In Java, everything is a referencePoint pt;pt = new Point(3, 4)ptx: 3 y: 4x: 3 y: 3moveToDiagonal(Point p) { p.setY(p.getX());}pIn Java, modifying a method parameter means modifying the original instance

  • almost everything is a referenceJava atomic types:intdoublebooleanetc

    C++ atomic types:intdoublebooletc In Java, modifying an atomically-typed parameter did NOT modify the original instance.

    In Java, atomic types are passed by copy. The same semantics hold for C++ atomic types

  • C/C++ Function ParametersIn C++, all function parameters are passed by copy even if theyre not of atomic typeWhy?First, a brief detour

  • Detour: Functions & MemoryEvery function needs a place to store its local variables. Collectively, this storage is called the stackThis storage (memory aka RAM), is a series of storage spaces and their numerical addresses Instead of using raw addresses, we use variables to attach a name to an addressAll of the data/variables for a particular function call are located in a stack frameMemory locationvoid aFunc(int x, int y) { double d1, d2; int i;}

  • Detour: Functions & Memory (cont)When a function is called, a new stack frame is set aside Parameters and return values are passed by copy (ie, theyre copied into and out of the stack frame)When a function finishes, its stack frame is reclaimed

    void aFunc(int x, int y) { double d1 = x + y;}int main(int argc, const char * argv[]) {int x = 7;aFunc(1, 2);aFunc(2, 3);return 0;}xyd1x7aFuncmain

  • C/C++ Function Parameters (cont.)In C++, all function parameters are passed by copy even if theyre not of atomic type Why?In C++, all variables exist on the stack by defaultIn C++, parameters are copied into the callees stack frameWell talk about Java parameter passing later (when we talk compare C++ and Java references)

  • Discussion Point IIExamine the code fragment below. Draw the stack frame(s) for some sample input. If you see any bugs, what are they? How would the program behave?void sillyRecursiveFunction(int i) { if(i == 0) { return; } else { sillyRecursiveFunction(i 1); }}

  • ArraysArrays are contiguous memory locations, and its name refers only to the address of the first elementIndexing into an array is the same as adding an offset to the address of the first elementWhen declaring an array, its size must be known at compile-time arrayName[ numElements ]

  • Arrays as function parametersArrays are not passed by copy. Instead, the address of the first element is passed to the functionNote how array parameters and non-parameter arrays behave identically funcName( ArrayType arrName[ ] )

    int sumOfArray( int values[], int numValues )

  • Discussion Point IIIWhy are arrays not passed by copy? Hint: the size of a stack frame is computed long before the program is run (specifically, at compile time)

  • PointersWhat if we had variables that contained addresses?They could contain addresses of anything!We could use these variables in functions to modify the callers data (we could implement Javas parameter-passing semantics!)

  • Pointers: vocabularyA pointer is a variable which contains addresses of other variablesAccessing the data at the contained address is called dereferencing a pointer or following a pointer

  • Pointer SyntaxDeclaring Pointers

    Declaring a pointer: * ptrName;

    ptrName is a variable which contains the address of something of type

    For example:int * nPtr1, * nPtr2;void aFunc( int aParam, int * ptrParam);Using Pointers

    Dereferencing a pointer:*ptrNameGo to the address contained in the variable ptrName

    Getting the address of a variable:&aVarGet the address of aVar

    For example:aFunc(myInt, &anotherInt);anInt = *myPtr * 4;*dinner = 100;

  • Pointers: Putting it all togetherThe code

    int * p;int q;

    p = &q*p = 5;Box Diagrams

    ps type is int pointer. qs type is int.

    Assign 5 to where p points (which is q).Memory Layout

    p contains the address of an int. q contains an int.Go to the address that p contains, and place a 5 there.

    p (8200)8196q (8196)5q

  • Pointers: Putting it all together (cont.)The code

    void doubleIt(int x, int * p){*p = 2 * x;}int main(int argc, const char * argv[]) {int a = 16;doubleIt(9, &a);return 0;}Box diagramMemory Layout

    9xp (8200)x (8196)16amaindoubleItpa (8192)1698192maindoubleIt

  • Pointer ArithmeticPointers are numbers, so you can do math on them! int * p = &a;Pointer p refers to an int, so adding 1 to p increments the address by the size of one int. The C/C++ expression for this is sizeof(int)*p = 200; *(p+1) = 300;

  • Pointers and ArraysPointers and arrays are (almost) interchangeablemyArray[3](8196)myArray[4](9000)int myArray[5];int * p = myArray;Given:These are equivalent: *p myArray[0] *(p+0) *myArray p[0] 0[p]myArray[2](8192)myArray[1](8188)myArray[0](8184)p(8180)8184

  • Discussion Point IVHow do pointers and arrays differ?Hint: how are pointers implemented in memory? Arrays?

  • ExerciseGet up and stretch!Do the worksheet exerciseThen, write a program to do the following:Read some numbers from the user (up to a max number of numbers)Calculate the average value of those numbersPrint the users values which are greater than the averageGet up and stretch again!

  • Pointer Problems Pointers can refer to other variables, but:Create an additional variableHave an ugly syntax

  • Function PointersFunctions are pieces of code in memoryPointers can point to functions.This syntax is U-G-L-Y (the ugliest in C)Notice that the name of the variable appears in the middle of the statement!You do not have to dereference a function pointer

    (*ptrName)(arg type list );Function pointers are not scary. They are useful!

  • Function Pointers - examplevoid foo(int i, char b);void bar(int i, char b);

    int main(void) {void (*p)(int,char);

    p = foo;p(1, c); // equivalent to foo(1, c);

    p = bar;p(2, b); // equivalent t