A C++ Crash Course

download A C++ Crash Course

of 44

  • date post

  • Category


  • view

  • download


Embed Size (px)


A C++ Crash Course. 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). Goals of Java. Java Simple Consistent Huge OO Focus - PowerPoint PPT Presentation

Transcript of A C++ Crash Course

  • A C++ Crash CourseUW 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)

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

  • The compilation ProcessPreprocessor.c.h.c.hCompilerLinkerexecutableLibrariesSource code (text)C/C++ code (text)Object code (bin)Native Executable (bin)PreprocesserResolves #define, #includeCompilerTranslates code to Machine Language. It outputs an object file. This code is not executableLinkerTakes object files and resolves references to functions and variables in different files

  • Declarations - (bad) Example

    int main(void) {int result;...

    result = add(20, 3);

    ...return 0;}

    int add(int a, int b) {return a + b;}

    What is wrong with the following code? Will it compile in C? in C++?Hint: It has to do with the declaration and use of add.

  • Declaration Regions

    int main(void) {int result;int add(int,int);...

    result = add(20, 3);

    ...return 0;}

    int add(int a, int b) {return a + b;}...int add(int,int);

    int main(void) {int result;...

    result = add(20, 3);

    ...return 0;}

    int add(int a, int b) {return a + b;}...

    Corrected Code 1 (local prototype)Corrected Code 2 (global prototype)

  • #define #define Tag SubstitutionReplaces all following occurrences of Tag with SubstitutionThe Substitution may be the empty stringDoes not replace Tag if it is inside quotation marks

    #define Tag(x,y,z) SubstitutionCreates a Function-like macro TagThe Substitution may refer to the parameters x, y, or zOnly items of the form Tag(x,y,z) will be replaced (Just plain Tag will be ignored)#define MAX_SIZE 80#define GET_FIELD(a,b) a->b

    int ar[MAX_SIZE];GET_FIELD(point, xCoord);GET_FIELD(lalala", f03j?);

    int ar[80];point->xCoord lalala->f03j?

  • Header FilesCommon Usages:Creates an informal module interface (No relation to Java interfaces)Provides documentationEach module usually has a header fileOften include the following:function prototypesstruct and class declarationstypedefsglobal variable declarationsLots of (high-level) commentsAbstracts code for optimization (less common)

  • #includeThere are two forms of #includeThey differ in the order in which directories are search for the given fileThe search order is implementation definedHere is the general pattern for different compilers:#include Searches the include path, then the current directory#include filenameSearches the current directory, then the include path

    #include essentially copies and pastes the given file into the current line

  • Header GuardsWrap each header file with the lines:

    #ifndef FILENAME_H#define FILENAME_H

    #endif /* FILENAME_H */Header Guards are a common C/C++ idiomThere is almost no reason to put things outside of header guards

  • Header Filepoint2d.h#ifndef POINT2D_H#define POINT2D_H

    struct Point2D { int x; int y; };typedef struct Point2D Point2D;

    /* returns the result of the vector addition of * a and b. */Point2D add(Point2D *a, Point2D *b);

    /* returns the result of the vector subtraction of * b from a */Point2D sub(Point2D *a, Point2D *b);

    #endif /* POINT2D_H */

  • ClassesRoots come from C-style structsFairly similar to Java classes in concept.Used to group related data and functions.Can be used to write OO code

    class Queue {public:Queue();void enqueue(int n);int dequeue();~Queue();private:int numElements;int capacity;int *queueData;};

  • Basic class SyntaxDeclaring a class: class [optional name] {[access modifier] member1; member2;

    [access modifier] member3; member4;} [instance list];

    Example: class Point2D{private:int x;int y;

    public:Point2D(int x, int y);int getX();int getY();} p1(2,3);

    Point2D p2(1,3);Point2D *p;

    Declaring a class without inheritance

  • Declaring & Defining methods/* point2d.h */

    #ifndef POINT2D_H#define POINT2D_H

    class Point2D{private:int x;int y;

    public:Point2D(int x, int y);int getX();int getY();};

    #endif /* POINT2D_H *//* point2d.cc */

    #include point2d.h

    Point2D::Point2D(int x, int y){x = 0; y = 0;}

    int Point2D::getX(){return x;}

    int Point2D::getY(){return y;}

  • ConstructorsConstructors have the same name as their classConstructors may not pass off control to another constructorA default (zero argument) constructor is provided when no other constructors declaredConstructors may invoke the constructors of their super class, and of their member variables via member-wise initialization.Constructors are functions that get called when a class is instantiated

  • DestructorsDestructors are have no return type and have the same name as their class with a ~ prepended.If no destructor is given, a trivial destructor, which calls the destructor for all elements is given.Destructors are called when a class is deallocated

  • InheritanceInheritance is specified by a : and a list of access specifiers + class names in the class declaration

    class Point2D{private:int x;int y;

    public:Point2D(int x, int y);int getX();int getY();};

    class ColorPoint2D : public Point2D{private:int color;

    public:ColorPoint2D(int x, int y, int color);int getColor();};

  • Inheritance continuedBase classes can be public, protected, or privateIn public inheritance, all public and protected members are inheritedIn protected inheritance, all public members from the base class become protectedIn private inheritance, all public and protected members become privateJava only has public inheritanceYou can call any ancestors class method using the scope resolution operator (::)

  • Dynamic MemoryDynamically sized memory in C and C++ must be manually managedDynamic memory is not necessarily much slower than static memoryAll allocated memory must be freed by the userDo not free memory twice (double free).Do not free memory that was allocated by youManual memory management allows for finer grained control of your programIts not that scary, nor that hard.

  • new, delete, delete[]the new operator allocates new memory, initializes it and returns a pointer to it.the delete operator deallocates memory allocated by newIf you allocate a new array, you must delete it with delete[] and not deleteImproper use of delete and delete[] will cause undefined behavior!Point2D *p = new Point;delete p;p = NULL;

    int *ar = new int[50];delete[] ar;ar = NULL;Example:

  • malloc, calloc, realloc, freeThese are C memory management functionsDo not mix them with the C++ ones! (that is, dont try to delete memory from malloc, etc.)These functions return void* (pointers to anything)They are not typesafeThey do not call initializers for the memoryThere is no realloc equivalent for C++Some low-level memory management may be faster with these functions, but dont bank on that.

  • 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 )

  • 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

  • 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

  • Function PointersFunctions are pieces of code in memoryPointers can point to functions.Notice that the name of the variable appears in the middle of the statement!You do not have to d